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] eleme开发者_运维问答nt 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.
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.
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]
精彩评论