6.Sorting the Hash : Dont really realise.reverse!


#1



On the exercise 6.Sorting the Hash , I dont understand what .reverse! is for~ tks

puts "What do you want to be?"
user = gets.chomp
words = user.split (" ")

frequencies = Hash.new(0)
puts frequencies

words.each do |words| frequencies[words] += 1 end

frequencies = frequencies.sort_by do |a,b| b end
frequencies.reverse!


Replace this line with your code.


#2

Hello :slight_smile:

This line:

frequencies = frequencies.sort_by do |a,b| b end

sorts the frequencies by the values (number of occurrences) in the ascending order:

[['b', 4], ['a', 1], ['c', 3]].sort_by do |a, b| b end
=> [["a", 1], ["c", 3], ["b", 4]]

But what if we are mainly interested in the elements, which occur most frequently? We should sort the frequencies in the descending order. And this is exactly why we need reverse!.

First, we sort frequencies in the ascending order and then we reverse the whole hash array getting the descending order.

[["a", 1], ["c", 3], ["b", 4]].reverse!
=> [["b", 4], ["c", 3], ["a", 1]]

reverse! is a mutating version of reverse. This means that these two statements are equivalent (when it comes to the result):

frequencies.reverse!
frequencies = frequencies.reverse

#3

WOW, that's so clear~~
I totaly understood, what .reverse! is for

thank you so much~!:grinning:


#4

You're very welcome :slight_smile:


#5

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