Ruby Array of Array Appending

kalasoo · 2014年04月29日 · 最后由 kalasoo 回复于 2014年04月29日 · 2329 次阅读

Gist Link

# Just found an interesting stuff

x = [[]] * 4    # [[], [], [], []]
x[0] << 1       # or x[0] .push 1
# => [[1], [1], [1], [1]]
x = [[]] * 4    # [[], [], [], []]
# just append an element to the first array of x

update:

x = [[], [], [], []]
x[0] << 1
# => [[1], [], [], []]
x = Array.new(4) { [] }

据我实验,楼主结论有误。

1] pry(main)> x = [[]] * 4
=> [[], [], [], []]
[2] pry(main)> x
=> [[], [], [], []]
[3] pry(main)> x[0] << 1
=> [1]
[4] pry(main)> x
=> [[1], [1], [1], [1]]
[5] pry(main)> -------------
[5] pry(main)*
[5] pry(main)*
[6] pry(main)> x = [[]] * 4
=> [[], [], [], []]
[7] pry(main)> x
=> [[], [], [], []]
[8] pry(main)> x << 1
=> [[], [], [], [], 1]
[9] pry(main)> x
=> [[], [], [], [], 1]
[10] pry(main)> x[0] << 1
=> [1]
[11] pry(main)> x
=> [[1], [1], [1], [1], 1]
[12] pry(main)>

我估计是这样,这个x = [[]] * 4 是同一个空数组 (的指针) 重复了 4 次,用 x=[[], [], [], []] 才是建立了四个不一样的空数组。

#1 楼 @santochancf よくやった、達也君 :thumbsup:

x = [[]] * 4

puts x.each {|a| puts a.object_id } 

x = Array.new(4) { [] }

puts x.each {|a| puts a.object_id }

# >> 70261926896280
# >> 70261926896280
# >> 70261926896280
# >> 70261926896280
# >> 70261926887120
# >> 70261926887100
# >> 70261926887060
# >> 70261926887040

#2 楼 @blacktulip 是我错了,我又重新试了一下。谢谢

需要 登录 后方可回复, 如果你还没有账号请 注册新账号