Sorting a hash in Ruby by its value first then its key -
i trying sort document based on number of times word appears alphabetically words when outputted this.
unsorted: 'the', '6' 'we', '7' 'those', '5' 'have', '3' sorted: 'we', '7' 'the', '6' 'those', '5' 'have', '3'
try this:
assuming:
a = { 'the' => '6', 'we' => '7', 'those' => '5', 'have' => '3', 'hav' => '3', 'haven' => '3' }
then after doing this:
b = a.sort_by { |x, y| [ -integer(y), x ] }
b
this:
[ ["we", "7"], ["the", "6"], ["those", "5"], ["hav", "3"], ["have", "3"], ["haven", "3"] ]
edited sort reverse frequencies.
Comments
Post a Comment