所以说我有一个3D数组,我按这样推送值:
@h = [[[]]]
@h.push(["cat", "mammal", 100.0])
@h.push(["lizard", "reptile", 300.0])
@h.push(["dog", "mammal", 200.0])
我如何通过第3个元素(浮点数)引用最大索引,然后引用索引的每个单独元素,在此示例中仅输出值“爬行动物”?
我试过了:
@h.each do |(x,y,z)|
if ( [x,y,z] == @h.max_by{|(x,y,z)| z} )
puts y
end
end
但它不会只给我“y”值。
谢谢!
答案 0 :(得分:1)
@h = [] # not [[[]]]
@h.push(["cat", "mammal", 100.0])
@h.push(["lizard", "reptile", 300.0])
@h.push(["dog", "mammal", 200.0])
max_ar = @h.max_by{|ar| ar[2]}
p max_ar[1] #=> "reptile"
# Your way is less usual. It works fine, but you're working too hard:
max_ar = @h.max_by{|(x,y,z)| z}
p max_ar[1] #=> "reptile"