Array of Arrays in ruby, passed by reference

前端 未结 2 1394
太阳男子
太阳男子 2020-12-11 22:06

I\'m trying to create a 5x5 matrix in Ruby filled with zeroes. The code I used was:

ruby-1.9.2-p290 :014 > a = Array.new(5, Array.new(5, 0))
 => [[0, 0         


        
相关标签:
2条回答
  • 2020-12-11 22:27

    I'm trying to create a 5x5 matrix in Ruby filled with zeroes. The code I used was:

    As others have pointed out, this is how arrays are supposed to work. Instead, you should use the block initializer:

    a = Array.new(5) { Array.new(5, 0) }
    

    In addition, however, if you're making a matrix, consider using the Matrix class in the standard library:

    require 'matrix'
     # => true 
    
    m = Matrix.build(5, 5) { 0 }
     # => Matrix[[0, 0, 0, 0, 0],
     #           [0, 0, 0, 0, 0],
     #           [0, 0, 0, 0, 0],
     #           [0, 0, 0, 0, 0],
     #           [0, 0, 0, 0, 0]] 
    
    m.determinant
     # => 0 
    
    0 讨论(0)
  • 2020-12-11 22:28

    Actually it is a feature.

    [...] it is created with size copies of obj (that is, size references to the same obj) [...]

    To create distinct arrays you can use e.g.

    a = Array.new(5){Array.new(5, 0)}
    

    or

    a = (1..5).map{Array.new(5, 0)}
    
    0 讨论(0)
提交回复
热议问题