ruby 中的数组数组,通过引用传递 [英] Array of Arrays in ruby, passed by reference
问题描述
我正在尝试在 Ruby 中创建一个 5x5 矩阵,其中填充了零.我使用的代码是:
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, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
然而,里面新创建的数组并不是单独的对象,而是对一个的引用.因此,当我尝试执行以下操作时:a[2][2] = 1
我得到:
However, the newly created arrays inside are not separate objects, but a reference to one. So when I try to do the following: a[2][2] = 1
I get:
=> [[0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0]]
这显然不是我想要的.检查对象 ID 确认:
Which is obviously not what I want. Checking objects ids confirms it:
ruby-1.9.2-p290 :020 > a.collect {|z| z.__id__}.uniq
=> [70253724580020]
我的问题是:这是错误还是功能?:) 我应该如何正确创建数组数组?
My questions is: is it a bug or feature? :) And how should I create array of arrays properly?
推荐答案
我正在尝试在 Ruby 中创建一个 5x5 矩阵,其中填充了零.我使用的代码是:
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) }
此外,如果您要制作矩阵,请考虑使用标准库中的 Matrix 类:
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
这篇关于ruby 中的数组数组,通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!