Milos Radosavljevic Milos Radosavljevic - 4 months ago 24
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"
mapa=Hash.new(0)
test.split(" ").each do |rec|
mapa[rec]+=1
end

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

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


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

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 ...
end

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.