1

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

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。有任何想法吗?

4

2 回答 2

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]
于 2013-05-02T11:35:53.747 回答
1

您可以映射arrayArray从子数组中获取第三个元素,然后使用该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 }
于 2013-05-02T10:44:36.257 回答