1

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

3 Answers 3

3

In ruby 1.8.7 there is a nice max_by method.

hash_example.values.max_by {|a| a[2]}
Sign up to request clarification or add additional context in comments.

Comments

2

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

2 Comments

Yours is the better analysis and the better solution. I withdraw.
Thanks for the in depth explination. It makes alot more sense now!
1

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

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.