从具有特定列(ruby)中的最大值的2d数组返回一行

时间:2013-05-02 10:16:10

标签: ruby arrays matrix row

就此而言,我创建了一个矩阵来查找请求的行:

require 'matrix'

m = Matrix[['IPE', '80', 2], ['HEB', '100', 1]]

index_of_specific_row = m.index(m.column(2).max)[0]

puts m.row(index_of specific_row)

#==> Vector['IPE', '80', 2]    # row with the max value of the third column

现在我正在寻找一种没有矩阵的等效解决方案。 但我被困在这里:

array = [['IPE', '80', 2], ['HEB', '100', 1]]

array.find { |row| row == max_value_of_the_third_column }

我无法弄明白max_value_of_the_third_column。有什么想法吗?

2 个答案:

答案 0 :(得分:4)

array = [['IPE', '80', 2], ['HEB', '100', 9],['HHB', '100', 6]]
array.max_by(&:last) #=> ["HEB", "100", 9]

更新:(How do I select a specific column (number_of_column instead of last)?

array = [['IPE', '80', 2], ['HEB', '100', 9],['HHB', '200', 6]]
p array.max_by{|i| i[1].to_i} #=>["HEB", "100", 9]
array = [['IPE', '80', 2], ['KEB', '100', 9],['HHB', '200', 6]]
p array.max_by{|i| i[0]} #=>["HEB", "100", 9] #=> ["KEB", "100", 9]

答案 1 :(得分:1)

您可以映射array以获取子阵列中第三个元素的Array,然后使用max方法:

array = [['IPE', '80', 2], ['HEB', '100', 1]]
max_value_of_the_third_column = array.map { |a| a[2] }.max
array.find { |a| a[2] == max_value_of_the_third_column }