首页 > 解决方案 > 空白数组在填充值时表现异常,具体取决于它的创建方式(Ruby)

问题描述

我有一个迭代填充的数组数组,但由于某种原因,它的定义方式似乎正在改变它的行为,即使它的结果等于其他方法的结果。所以这里是代码:

@height = 5
@nums = (1..60).to_a

@grid = []

@height.times do # Method one for making the grid
  @grid << []
end

print @grid, "\n" # Print the grid, shows [[], [], [], [], []] as expected

@grid2 = Array.new(@height, []) # Cleaner way of making the grid

print @grid2, "\n" # Print the grid, shows [[], [], [], [], []] as expected

print @grid2 == @grid, "\n" # Are they equal? returns true as expected

@grid = @grid2 # Commenting out this line changes the behavior of the output

@nums.length.times do |n|         # Fill the grid with our numbers
  @grid[n % @height] << @nums[n]
end

@grid.each do |i|   # Display the grid
  print i, "\n"
end

标签: arraysruby

解决方案


推荐阅读