Search code examples
ruby-on-railsrubyhashmaxby

Pushing max hash key-values into an array in Ruby?


I have a hash called count, defined as count = {4=>2, 5=>3, 6=>3, 7=>1}.

I want to take the max value, and then push the key that corresponds to that value into an array, so I do this:

array = []
array.push(count.max_by{|k,v| v}[0])

=>> [5]

However, 6 also has the value 3, which is another maximum value. How do I push this value into the array so I get [5,6] instead of just [5]?


Solution

  • This is the way to choose the max values of the hash:

    count.values.max
    => 3
    

    Use the select method on the hash:

    count.select{ |k, v| v == count.values.max }
     => {5=>3, 6=>3}
    

    Get the keys:

    count.select{ |k, v| v == count.values.max }.keys
     => [5, 6]
    

    And finally assign to an array:

    array = count.select{ |k, v| v == count.values.max }.keys