我有这个哈希:
h = {
124 => ["shoes", "59.99"],
456 => ["pants", "49.50"],
352 => ["socks", "3.99"]
}
Run Code Online (Sandbox Code Playgroud)
每个值都有两个元素.他们是一个名称(如"shoes","pants","socks")和价格(例如"59.99","49.50"和"3.99").我需要选择价格最高的价值.这124对价格来说至关重要"59.99".如何选择价格最高的哈希?
我试过这个:
h.select{ |x| x[1] }.max
#=> [456, ["pants", "49.50"]]
Run Code Online (Sandbox Code Playgroud)
但这给了我最大值并返回键456.
最惯用的可能就是:
h.max_by { |_, v| v.last.to_f }
#=> [124, ["shoes", "59.99"]]
Run Code Online (Sandbox Code Playgroud)
您可以使用如下括号挖掘结构:
h = {
124 => ["shoes", "59.99"],
456 => ["pants", "49.50"],
352 => ["socks", "3.99"]
}
h.max_by{|_, (_, price)| price.to_f}
# => [124, ["shoes", "59.99"]]
Run Code Online (Sandbox Code Playgroud)