user3576036
user3576036

Reputation: 1425

Collecting and comparing ruby hashes inside array

I have a ruby Array that has multiple hashes inside it. Looks as follows:

arr_hsh = [
      {
        'name': 'Outdoor',
        'game_code': 'C5',
        'score': '61.68',
      },
      {
        'name': 'Indoor',
        'game_code': 'C6',
        'score': '37.54',
      }
]

I want to return game_code and score pair with the highest score value.

How can I achieve this without doing multiple iterations.

If I do

arr_hsh.collect {|p| "#{p[:game_code]}: #{p[:score]}"} 

Its just returning this

["C5: 61.68", "C6: 37.54"]

but I want [C5 => 61.68]

How can I get this?

Upvotes: 0

Views: 46

Answers (1)

iGian
iGian

Reputation: 11183

You can use the Enumerable#max_by method in this way and Object#then (or Object#yield_self for older versions of Ruby):

arr_hsh.max_by { |h| h['score'] }.then { |res| { res[:game_code] => res[:score] } }
#=> {"C5"=>"61.68"}

The first part is working this way:

arr_hsh.max_by { |h| h['score'] }
#=> {:name=>"Outdoor", :game_code=>"C5", :score=>"61.68"}

The second part takes this output and builds the final Hash, if this is the object you want or whathever.

Consider to convert the score to float, currently is a string.

Upvotes: 5

Related Questions