开发者

Iterating through multiple values in a hash and returning a value

开发者 https://www.devze.com 2022-12-11 16:01 出处:网络
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 woul

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,开发者_JAVA技巧 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


In ruby 1.8.7 there is a nice max_by method.

hash_example.values.max_by {|a| a[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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号