以下是您不必担心将单元格键与 delta 匹配的方法:
cells = cells.map {|cell| [cell,delta].transpose.map {|value| value.reduce(:+)}}
一步步:
cells = cells.map { |cell| # => [0,0]
combined = [cell, delta] # => [[0,0], [1,0]]
transposed = combined.transpose # => [[0, 1], [0, 0]]
new_c = transposed.map { |value| # => [0, 1]
value.reduce(:+) # => 1, => 0
}
new_c # => [1,0] As expected for first cell.
}
cells # => [[1,0],[1,1]] Final result
使用另一个示例数据:
cells = [[0,0],[1,1],[2,2]]
delta = [1,1]
plug = Proc.new {
cells = cells.map { |cell| [cell, delta].transpose.map { |value| value.reduce(:+) } }
}
plug.call # => [[1, 1], [2, 2], [3, 3]]
plug.call # => [[2, 2], [3, 3], [4, 4]]
plug.call # => [[3, 3], [4, 4], [5, 5]]
plug.call # => [[4, 4], [5, 5], [6, 6]]
plug.call # => [[5, 5], [6, 6], [7, 7]]
另一个:
cells = [[0,0,0],[0,1,2],[1,2,3],[2,3,4]]
delta = [3,2,1]
plug.call # => [[3, 2, 1], [3, 3, 3], [4, 4, 4], [5, 5, 5]]
plug.call # => [[6, 4, 2], [6, 5, 4], [7, 6, 5], [8, 7, 6]]
plug.call # => [[9, 6, 3], [9, 7, 5], [10, 8, 6], [11, 9, 7]]
plug.call # => [[12, 8, 4], [12, 9, 6], [13, 10, 7], [14, 11, 8]]
plug.call # => [[15, 10, 5], [15, 11, 7], [16, 12, 8], [17, 13, 9]]
希望这能更好地回答你的问题。