就此而言,我创建了一个矩阵来查找请求的行:
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
。有什么想法吗?
答案 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 }