Ruby 2D array assignment

前端 未结 1 998
予麋鹿
予麋鹿 2021-01-26 01:08

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)))
    @gr         


        
相关标签:
1条回答
  • 2021-01-26 01:48

    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:

    Note that the second argument populates the array with references to the same object. Therefore, it is only recommended in cases when you need to instantiate arrays with natively immutable objects such as Symbols, numbers, true or false.

    To create an array with separate objects a block can be passed instead. This method is safe to use with mutable objects such as hashes, strings or other arrays:

    Array.new(4) { Hash.new } #=> [{}, {}, {}, {}]
    

    This is also a quick way to build up multi-dimensional arrays:

    empty_table = Array.new(3) { Array.new(3) }
    #=> [[nil, nil, nil], [nil, nil, nil], [nil, nil, nil]]
    

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

    0 讨论(0)
提交回复
热议问题