tags:

views:

70

answers:

3

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
+2  A: 

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
Simone Carletti
Yours is the better analysis and the better solution. I withdraw.
Carl Smotricz
Thanks for the in depth explination. It makes alot more sense now!
Matt
+3  A: 

In ruby 1.8.7 there is a nice max_by method.

hash_example.values.max_by {|a| a[2]}
Greg Dan
+1  A: 

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

hash_example.values.collect{|a|a[2]}.max
EmFi
how do I take my value from max and return a different element in the same array? Obviously dog is 3 for .max but how do I puts that becasue the element in that array is .max I want to know print the string Dog? I didn't fully understand the .inject block
Matt