tags:

views:

57

answers:

2

So I semi-asked this in another thread about how to get .max and return a value to a screen. All where very good answers, I just didn't ask the entire question. I ended up going with:

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

 h =hash_example.values.collect{|a|a[0]}.max #change .max value based on element
 puts the a[1] element based on what is returned in h because of .max of a[0].max

The problem is now I want to take h (the .max value found) and based on finding that element return a different element from the same array in the next line of code. To further elaborate lets say the above code found dog as .max. How do I go about returning brown or 3 to the screen in the next line of code?

 puts hash_example.some_method_here{block of  useful code using the h value} ?

I'm probably looking into this the wrong way or is it just a simple puts statment ? I've tried some nesting in the block but I'm definetly not nesting it correctly. .inject and .map I think are the right direction but I'm not writing the block correctly.

+1  A: 

You're probably best off sorting the hash values, and taking the last one (as the max value), then working from there.

>> h = {777 =>["dog","brown",3], 123=>["cat","orange",2]}
=> {777=>["dog", "brown", 3], 123=>["cat", "orange", 2]}
>> h.values.sort_by{|a|a[0]}.last[1]
=> "brown"

The sort_by method accepts a block that describes what you want to sort by, relative to a single element - in this case it's using the first array element.

Jamie Macey
This is what I was going to suggest, too.
glenn mcdonald
+1  A: 

Here is a way of finding the max that will also give you the other array elements...

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

>> e.values.transpose[0].max
=> "dog"

So we can rewrite the code from the top...

x = e.values
t = x.transpose[0]
x[t.index t.max]

Which returns ["dog", "brown", 3]

DigitalRoss
BTW, note that the `[0]` is unrelated to the fact that "dog" is first, rather, it peels off what's now a row of `["dog", "cat", "zebra", "cheetah", "serval", ...]`. This technique also gets you rows like `["brown", "orange", ...]` and `[3, 2, ...]`. (Those would be the `[1]` and `[2]` rows.)
DigitalRoss
I had another thought on how to solve this. Can I find a .max of elements and return the hash key? Take the hash key and return the element in the array I want to display. I have no idea how to return the key from .max though and use that key to return the element I want?
Matt