user2963093
user2963093

Reputation: 47

Max value of nested array in hash

What I have:

hash = {id =>[string, number], id =>[string, number]}

I need to get the max value of number. I have been able to do this, but when I puts it. I get:

id
string
number

What I need please

id string number

This is what I've tried:

This brings the max value to the top of list, but I need to exclude the rest of the list.

hash.each{|x, y| puts "#{x} #{y[0]} #{y[1]}"}.max

This returns the max value but displays it vertically

puts hash.max_by{|y| "#{y}"} 

I have tried numerous other things and am having a hard time wrapping my head around this one.

Not sure if it matters but I am read this in from a file into a hash, the number is a float

Upvotes: 0

Views: 837

Answers (2)

Geremy
Geremy

Reputation: 2445

I would re-arrange the hash with number as the key, then use sort_by(): http://www.rubyinside.com/how-to/ruby-sort-hash

Upvotes: 0

Andrew Marshall
Andrew Marshall

Reputation: 96934

The max here doesn’t do anything (since it is called on hash and its return value never used):

hash.each{|x, y| puts "#{x} #{y[0]} #{y[1]}"}.max

This is the same as doing puts on an array (since that’s what max_by returns), which prints each element on a separate line. You’re also unnecessarily converting your number to a string (which can result in unexpected comparison results):

puts hash.max_by{|y| "#{y}"}

Instead let’s just get the max key/value pair:

max = hash.max_by { |id, (string, number)| number }
#=> ["the-id", ["the-string", 3.14]]

Now we can flatten and join the array before puts-ing it:

puts max.flatten.join(' ')
# prints: the-id the-string 3.14

Upvotes: 4

Related Questions