阵列中的红宝石阵列,通过引用传递 [英] Array of Arrays in ruby, passed by reference
问题描述
我试图创建用零填充在Ruby中一个5x5的矩阵。在code我用的是:
红宝石1.9.2-P290:014>一个= Array.new(5,Array.new(5,0))
= GT; [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
我得到:
=> [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]]
这显然不是我想要的。检查对象IDS证实了这一点:
红宝石1.9.2-P290:020> a.collect {| Z | ž.__ ID __}。uniq的
= GT; [70253724580020]
我的问题是:这是一个错误或功能? :)我应该怎么创建数组的数组正确?
我试图创建用零填充在Ruby中一个5x5的矩阵。在code我用的是:
块引用>正如其他人所指出的那样,这是数组应该如何工作。相反,你应该使用块初始化:
A = Array.new(5){Array.new(5,0)}
此外,然而,如果你正在做一个矩阵,考虑使用标准库Matrix类
要求'矩阵'
#=>真正M = Matrix.build(5,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]]m.determinant
#=> 0I'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]]
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]]
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?
解决方案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
这篇关于阵列中的红宝石阵列,通过引用传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!