新手问题 请教大家一个关于 Ruby 的 Array 的问题?

HyeKyoZ-github · 2017年09月26日 · 最后由 HyeKyoZ-github 回复于 2017年09月27日 · 1323 次阅读
a = Array.new 3 do
      [0, 0, 0]
    end
a[0][1] = 2

# [[0, 2, 0], [0, 0, 0], [0, 0, 0]]
p a

###################

b = [0, 0, 0]
c = Array.new 3 do
      b
    end 
c[0][1] = 2

# [[0, 2, 0], [0, 2, 0], [0, 2, 0]]
p c

###################

d = Array.new(3, [0, 0, 0])
d[0][1] = 2

# [[0, 2, 0], [0, 2, 0], [0, 2, 0]]
p d

###################

根据以上结果产生的问题:三种初始化的结果为什么不同?a 与 d?,d 与 c?

测试环境:ruby 2.4.2p198 (2017-09-14 revision 59899) [x86_64-darwin17]

谢谢大家!


引用
引用

因为在 Ruby 中数组是可变对象,而且赋值 / 作为参数传递时,传递的都是引用。 关于 Ruby 的引用: https://en.wikibooks.org/wiki/Ruby_Programming/Introduction_to_objects

再就是 Array.new 方法的不同用法的语义,官方文档也是有介绍的: http://ruby-doc.org/core-2.4.1/Array.html#method-c-new

官方文档已经讲了很清楚了

new(size=0, default=nil) new(array) new(size) {|index| block }

In the first form, if no arguments are sent, the new array will be empty. When a size and an optional default are sent, an array is created with size copies of default. Take notice that all elements will reference the same object default.

HyeKyoZ-github 关闭了讨论。 09月27日 10:45
需要 登录 后方可回复, 如果你还没有账号请 注册新账号