在ruby中排序多维数组

JP *_*shy 7 ruby

我有以下数组:

[["2010-01-10", 2], ["2010-01-09", 5], ["2009-12-11", 3], ["2009-12-12", 12], ["2009-12-13", 0]]

我只想按每组中的第二个值对其进行排序并返回最高值,就像我希望输出12与上面的给定输入一样.

更新

我可能会补充一点,我使用to_a哈希来使用这个数组,所以如果有相同的哈希可以做得更好.

YOU*_*YOU 29

按第二个值排序

x=[["2010-01-10", 2], ["2010-01-09", 5], ["2009-12-11", 3], ["2009-12-12", 12], ["2009-12-13", 0]]

x.sort_by{|k|k[1]}
=> [["2009-12-13", 0], ["2010-01-10", 2], ["2009-12-11", 3], ["2010-01-09", 5], ["2009-12-12", 12]]
Run Code Online (Sandbox Code Playgroud)


小智 8

调用sort哈希上的方法对其进行排序.

hash = hash.sort { |a, b| b[1] <=> a[1] }
Run Code Online (Sandbox Code Playgroud)

然后将您的哈希值转换为数组并提取第一个值.

result = hash.to_a[0][1]
Run Code Online (Sandbox Code Playgroud)


Chr*_*ung 7

在你的哈希上使用它:

hash.values.max
Run Code Online (Sandbox Code Playgroud)

如果您只需要最高元素,则无需对其进行排序!