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

bop*_*ard 0 ruby arrays ruby-on-rails 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]]
Run Code Online (Sandbox Code Playgroud)

我需要能够找到“Patient 2”-“8/2/2014”的索引,这当然是 array[2][2] 以便我可以将它的值从 0 更改为其他值。我如何使用我布置的列名和行名找到它?

非常感谢。

Uri*_*ssi 5

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

matrix.find { |x| x[0] == "8/2/2014" }
# => ["8/2/2014", 0, 0, 0] 
Run Code Online (Sandbox Code Playgroud)

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

matrix[0].index("Patient 2")
# => 2
Run Code Online (Sandbox Code Playgroud)

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

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]] 
Run Code Online (Sandbox Code Playgroud)