我想在某一个数组中插入元素,代码如下:
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]
更加摸不着头脑了……求指教……
The 10 empty arrays created by this method are the same Object
If you want to create different Objects, please use the following method.
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?