# Ruby 二维数组生成小陷阱

hlxwell · 2018年02月09日 · 最后由 hlxwell 回复于 2018年02月10日 · 1244 次阅读

``````[1] pry(main)> matrix = [[0] * 5] * 10
=> [[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, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]]
[2] pry(main)> matrix[1][1] = 2
=> 2
[3] pry(main)> matrix
=> [[0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0], [0, 2, 0, 0, 0]]
``````

``````ary_memcpy(ary2, 0, t, ptr);
while (t <= len/2) {
ary_memcpy(ary2, t, t, RARRAY_CONST_PTR(ary2));
t *= 2;
}
if (t < len) {
ary_memcpy(ary2, t, len-t, RARRAY_CONST_PTR(ary2));
}
``````

msg7086 回复

``````[1] pry(main)> a = [0] * 5
=> [0, 0, 0, 0, 0]
[2] pry(main)> a
=> [0, 0, 0, 0, 0]
[3] pry(main)> a[2] = 4
=> 4
[4] pry(main)> a
=> [0, 0, 4, 0, 0]  <=  按道理这个应该是 [4,4,4,4,4] 因为所有的都是指向同一个地方。
``````

``````# pry
[1] pry(main)> s = ['0']*4
=> ["0", "0", "0", "0"]
[2] pry(main)> s[0] = '1'
=> "1"
[3] pry(main)> s
=> ["1", "0", "0", "0"]
[4] pry(main)> s[1].replace '2'
=> "2"
[5] pry(main)> s
=> ["1", "2", "2", "2"]
[6] pry(main)> s.map &:object_id
=> [46944791677080, 46944791865940, 46944791865940, 46944791865940]
[7] pry(main)>
``````

``````值 [[0 0] [0 0]]

a[0][0] = 2

``````

@hlxwell 还记得 C# 的 byVal 和 byRef 么? 在 Ruby 里

`4, true, 1.3, nil` 这些都是 value type,

`5..6, "foo", [4,4,4], {a: 3}, Object.new` 这些是 reference type ...

luikore 回复