Milos Radosavljevic Milos Radosavljevic - 1 year ago 121
Ruby Question

Sorting Hash by value

I want to sort my has by value.I am tried to sort my hash this way and it does not work, I don't know why.
This is my code:

test="neki text sa recima neki sa i jos neki aa"
test.split(" ").each do |rec|

mapa.sort_by {|a,b| b}.reverse

mapa.each do |key, value|
puts "#{key} #{value}"

the output is :

neki 3
text 1
sa 2
recima 1
i 1
jos 1
aa 1

It doesn't do anything to the HASH :/
Can someone explain to me why it does not work?

if you give me a MINUS please explain in the comment what I did to deserve it so I know where to improve. :)

Answer Source

Enumerable#sort_by never promised to sort the enumerable inplace. It returns the result:

puts mapa.sort_by {|a,b| -b}
#⇒ sorted

or, in more idiomatic manner:

mapa.sort_by(&:last).reverse.each do |k, v|
  puts ...

Please note, that when examining the output in irb, the order might not correspond to the real order of elements in a hash, since irb (with print formatters installed) has it’s own ideas on how to output hashes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download