Matt
Matt

Reputation: 557

Iterating through multiple values in a hash and returning a value

I have a hash:

  hash_example = {777 =>[dog,brown,3], 123=>[cat,orange,2]}

I want to go through the hash array value and determine based on the third element which pet is the oldest age. I would choose the max for my method, the part where I figure out which value is associated with max and returning it to the screen is the part I am not getting, or am I completly lost? I threw the third value in there for educational purpose on how to compare different elements of the array.

b = hash_example.values.max{|k,b,c| b<=>c } 
print b

Upvotes: 1

Views: 1214

Answers (3)

EmFi
EmFi

Reputation: 23450

Similar to Greg Dan's response for earlier versions of Ruby.

hash_example.values.collect{|a|a[2]}.max

Upvotes: 1

Greg Dan
Greg Dan

Reputation: 6298

In ruby 1.8.7 there is a nice max_by method.

hash_example.values.max_by {|a| a[2]}

Upvotes: 3

Simone Carletti
Simone Carletti

Reputation: 176402

max iterates all items returned by values and each item is an array itself. That's the point you are missing.

> hash_example.values
# => [["dog", "brown", 3], ["cat", "orange", 2]]

max doesn't return the value you are comparing against, instead, it returns the item that satisfies the comparison. What does it mean in practice? Here's the "working" version of your script

> hash_example.values.max{|a,b| a[2]<=>b[2] }
# => ["dog", "brown", 3]

As you can see, the returned value is the full item not the element used for the comparison. If you only want the third element you have to use inject.

> hash_example.values.inject(0) {|t,i| i[2] > t ? i[2] : t }
# => 3

Upvotes: 2

Related Questions