Ruby中二维数组插入元素的问题
天蓬老师
天蓬老师 2017-04-21 11:18:00
0
3
769

我想在某一个数组中插入元素,代码如下:

foo = Array.new(10,[])
foo[0] << 1
puts foo.to_s

输出的结果是

[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]

这是为什么啊?

如果是哈希的话

bar = Hash.new([])
bar[0] << 1
puts bar.to_s
puts bar[1].to_s

输出的结果是

{}
[1]

更加摸不着头脑了……求指教……

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(3)
左手右手慢动作
foo = Array.new(10,[])

The 10 empty arrays created by this method are the same Object

If you want to create different Objects, please use the following method.

foo = Array.new(10) { Array.new }

Reference: http://ruby-doc.org/core-2.0.0/Array.html#label-Creating+Arrays

迷茫

To add to the above, all object_ids are the same
foo.map(&:object_id)
=> [9298880, 9298880, 9298880, 9298880, 9298880, 9298880, 9298880, 9298880, 9298880, 9298880]

刘奇

I usually use map.
(1..10).map {[]}

But I still have a question, why is it still the same Array?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template