Home  >  Q&A  >  body text

Ruby中二维数组插入元素的问题

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

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]

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

天蓬老师天蓬老师2713 days ago698

reply all(3)I'll reply

  • ringa_lee

    ringa_lee2017-04-21 11:20:00

    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

    reply
    0
  • 迷茫

    迷茫2017-04-21 11:20:00

    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]

    reply
    0
  • 怪我咯

    怪我咯2017-04-21 11:20:00

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

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

    reply
    0
  • Cancelreply