Create multiple arrays in one line

后端 未结 1 1380
花落未央
花落未央 2021-01-29 02:30

I did:

a, b = Array.new(2, [0, 0])
a[0] = 1

I have:

a # => [1, 0]

I have a problem with b, wh

1条回答
  •  北恋
    北恋 (楼主)
    2021-01-29 03:01

    This is mentioned here:

    When sending the second parameter (to Array.new), the same object will be used as the value for all the array elements:

    So, as @mudasobwa already suggested in the comments, you need to use the block version which uses the result of block for each element:

    a, b = Array.new(2) { [0, 0] }
     => [[0, 0], [0, 0]]
    
    a[0] = 1
    
    a
     => [1, 0]
    
    b
     => [0, 0]
    

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