本文介绍了Ruby 2D数组分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个tic-tac-toe board类.参见下文:

class Board
  attr_accessor :grid

  def initialize(grid = Array.new(3, Array.new(3, nil)))
    @grid = grid
  end

  def place_mark(position, symbol)
    @grid[position[0]][position[1]] = symbol
  end
end

每当我调用place_mark方法并尝试将符号分配给2D数组中的元素时,整个列都会被分配.

board = Board.new
board.place_mark([0,0], :x)

会导致

[[:X, nil, nil],
 [:X, nil, nil],
 [:X, nil, nil]]

期望的结果

[[:X , nil, nil],
 [nil, nil, nil],
 [nil, nil, nil]]

我找到了解决问题的方法,在initialize方法中,我只需要分配网格的默认值,如下所示:

def initialize(grid = [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]])
  @grid = grid
end

然后place_mark方法就可以了.

所以我的问题是两个不同的数组声明如何不同,从而使它们以这种方式运行?

解决方案

问题是Array.new(3, Array.new(3, nil))会给您一个具有相同数组的数组三次.

就像这样做:

x = Array.new(3, nil)
grid = Array.new(3, x)

所以您有一个包含x的数组三次.您真的想要三个单独的数组,每个数组可以有自己的值.

每个 http://ruby-doc.org/core-2.3. 1/Array.html :

最后一个示例正是您要寻找的.

So I have a tic-tac-toe board class. See below:

class Board
  attr_accessor :grid

  def initialize(grid = Array.new(3, Array.new(3, nil)))
    @grid = grid
  end

  def place_mark(position, symbol)
    @grid[position[0]][position[1]] = symbol
  end
end

Whenever I call the place_mark method, and tried to assign a symbol to an element in the 2D array, the entire column gets assigned.

board = Board.new
board.place_mark([0,0], :x)

Would result in

[[:X, nil, nil],
 [:X, nil, nil],
 [:X, nil, nil]]

Where the desired result is

[[:X , nil, nil],
 [nil, nil, nil],
 [nil, nil, nil]]

I found a solution to my problem, in the initialize method, I just need to assign the default value of grid like this:

def initialize(grid = [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]])
  @grid = grid
end

Then the place_mark method works just fine.

So my question is how are the two different array declarations different that would make them behave this way?

解决方案

The issue is that Array.new(3, Array.new(3, nil)) gives you an array with the same array in it three times.

It's like doing this:

x = Array.new(3, nil)
grid = Array.new(3, x)

So you have an array containing x three times. You really want three separate arrays that can each have their own values.

Per http://ruby-doc.org/core-2.3.1/Array.html:

That last example is exactly what you're looking for.

这篇关于Ruby 2D数组分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 02:30
查看更多