Sort_by


#1

<PLEASE USE THE FOLLOWING TEMPLATE TO HELP YOU CREATE A GREAT POST!>

<Below this line, add a link to the EXACT exercise that you are stuck at.>

Sorting the hash
<In what way does your code behave incorrectly? Include ALL error messages.>

Right result but strange method.

sort_by creates an array of 2-element arrays which you can then sort or whatever. In the quoted code, copied from the tutorial and not mine by the way, we end up with the variable ‘frequencies’ as such a 2D array when it starts the program as a hash. Changing the type of a variable in the middle of a program seems a weird thing to do; most languages with declared typed variables wouldn’t allow it and it seems confusing. Why do it?

```frequencies = Hash.new(0)
words.each {|w| frequencies[w] +=1}
frequencies = frequencies.sort_by do |item, count|
  count
end

#2

Maybe read
https://stackoverflow.com/questions/17180284/subtle-difference-between-sort-and-sort-by


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.