Ruby在多维数组中按列和行查找

时间:2014-08-12 13:07:50

标签: ruby-on-rails ruby arrays multidimensional-array

所以这就是我的数组的样子

[["Date", "Patient 1", "Patient 2", "Patient 3"],
["8/1/2014",0,0,0]
["8/2/2014",0,0,0]
["8/3/2014",0,0,0]]

我需要能够找到“Patient 2” - “8/2/2014”的索引,这当然是数组[2] [2],这样我就可以将它的值从0改为其他。如何使用我已经列出的列名和行名找到它?

非常感谢。

2 个答案:

答案 0 :(得分:4)

要查找行,您可以使用find并将值与每行中的第一个元素进行比较:

matrix.find { |x| x[0] == "8/2/2014" }
# => ["8/2/2014", 0, 0, 0] 

要查找列索引,可以在第一个数组上使用index

matrix[0].index("Patient 2")
# => 2

您可以将其包装在方法中:

def change_matrix(matrix, row, col, new_val)
  matrix.find { |x| x[0] == row }[matrix[0].index(col)] = new_val
end

change_matrix(matrix, '8/2/2014', 'Patient 2', 5)

matrix
# => [["Date", "Patient 1", "Patient 2", "Patient 3"], 
#     ["8/1/2014", 0, 0, 0], 
#     ["8/2/2014", 0, 5, 0], 
#     ["8/3/2014", 0, 0, 0]] 

答案 1 :(得分:2)

您可以执行以下操作:

a = [["Date", "Patient 1", "Patient 2", "Patient 3"],["8/1/2014",0,0,0],["8/2/2014",0,0,0],["8/3/2014",0,0,0]]
b = a.transpose

print a[0][1] + " " + b[0][1]

演示:http://runnable.com/U-oULwIJWFYZpeOx/transpose-for-ruby