+ 1

Some things i'm unsure about regarding hashes

This is mostly in conjunction with do loops, so i have made a simple program that outputs the frequency of numbers used in a sentence: https://code.sololearn.com/cgXkxOEYe0kr 1. what's implicitly going on at line 21? i know this line of code iterates through and sorts the array, but what exactly is going on, more specifically with the block that comes after the items and amount indexes are declared? 2. what's going on with the do loops indexes at line 24? i'm assuming that by default, the first value is passed into the hash as a key, whilst the second is passed as an amount. 3. this is more general: i'm generally new to ruby, only started learning it this month; is ruby an implicit language in general: is it's syntax less direct and straightforward when it comes to being able to understand it's associated logic? if that wasn't clear, i'll give an example: "frequencies = frequencies.sort_by {|item, amount| amount }" sorts the array, but isn't nessecarily immediately straightforward in signalling such,

23rd Jan 2018, 9:47 PM
X-1
X-1 - avatar
1 Antwort
+ 1
1. The built in sort can only handle numbers. Since you can store pretty much anything in a hash, not only numbers, ruby will need to transform your hash into a list of numbers before it can sort it. More or less the sort_by function is saying: "here's the key (in your case word name) and the value (in your case number of occurences), now tell me how to make a number out of that so I can sort it." Amount happens to be a number and also the thing you want to sort by, so you just return that. 2. ".each" loops over each element in your hash. the thing with the |indices| is pretty much a function. So, for each element in the hash, execute that function which is between the do and the end. 3. The sort_by is pretty common and most languages have it, but ruby's syntax is a bit unusual, yeah. It's unlike other languages but not necessarily more difficult. Just takes some getting used to. All these methods like sort_by and each also exist for arrays, maybe check those out first, if hashes are still unclear.
23rd Jan 2018, 10:35 PM
Schindlabua
Schindlabua - avatar