【发布时间】:2013-12-12 17:54:02
【问题描述】:
我正在尝试向 ruby 中的二维数组添加更多元素,但 .push 方法不起作用。在截图中,我打印出了所有元素,最后一行是数组。
代码如下:
def solution(a)
x = 0
y = 1
coordinates = [[0, 0]]
a.each_with_index do |i, index|
next_coordinate = coordinates[coordinates.length-1]
case (index%4)
when 0
next_coordinate[y] += i
when 1
next_coordinate[x] += i
when 2
next_coordinate[y] -= i
else
next_coordinate[x] -= i
end
puts next_coordinate.to_s
coordinates.push(next_coordinate)
end
return coordinates.to_s
end
a = [1, 3, 2, 5, 4, 4, 6, 3, 2]
puts solution(a)
【问题讨论】:
-
预期输出是什么?
-
[[0, 0], [0, 1], [3, 1], [3, -1], [-2, -1], [-2, 3], [ 2, 3], [2, -3], [-1, -3], [-1, -1]]
-
请考虑将您的结果作为文本而不是屏幕截图添加到问题中。屏幕截图不能剪切和粘贴,而且更难阅读。您的预期输出也应该包含在问题本身中。