Pressing a string into an array inside the array gives an unexpected result

I have an array in Ruby consisting of 5 empty arrays. I am trying to use the << operator to insert a string into the first array, but the result is that the string falls into ALL arrays. Please help me figure this out.

Expected Result:

 # => [["car"], [], [], [], []] 

but instead I get:

 # => [["car"], ["car"], ["car"], ["car"], ["car"]] 

irb dump:

 1.9.3-p194 :001 > output = Array.new(5, []) => [[], [], [], [], []] 1.9.3-p194 :002 > output.inspect => "[[], [], [], [], []]" 1.9.3-p194 :003 > output[0].inspect => "[]" 1.9.3-p194 :004 > output[0] << "car" => ["car"] 1.9.3-p194 :005 > output.inspect => "[[\"car\"], [\"car\"], [\"car\"], [\"car\"], [\"car\"]]" 
+6
source share
3 answers

All of them are one and the same object:

 ree-1.8.7-2012.02 :001 > output = Array.new(5, []) => [[], [], [], [], []] ree-1.8.7-2012.02 :002 > output[0] => [] ree-1.8.7-2012.02 :003 > output[0].object_id => 2219989240 ree-1.8.7-2012.02 :004 > output[1].object_id => 2219989240 ree-1.8.7-2012.02 :005 > output[2].object_id => 2219989240 ree-1.8.7-2012.02 :006 > output[3].object_id => 2219989240 ree-1.8.7-2012.02 :007 > output[4].object_id => 2219989240 ree-1.8.7-2012.02 :008 > 

Try the following:

 ree-1.8.7-2012.02 :008 > output = [] => [] ree-1.8.7-2012.02 :009 > 5.times{output << []} => 5 
+6
source

They all have the same object identifier, as Pedro Nascimento pointed out, if arrays are initialized this way. You can get around this using a similar syntax to create your nested arrays:

 irb(main):047:0> output = Array.new(5) {[]} => [[], [], [], [], []] irb(main):048:0> output.each {|i| puts i.object_id} 10941700 10941680 10941660 10941640 10941620 

So, your application to output[0] will work as expected:

 irb(main):049:0> output[0] << "cat" => ["cat"] irb(main):050:0> output => [["cat"], [], [], [], []] 
+5
source

The code

 output = Array.new(5, []) 

trying to create only one copy of an object,

So

 ree-1.8.7-2012.02 :003 > output[0].object_id => 2219989240 ree-1.8.7-2012.02 :004 > output[1].object_id => 2219989240 ree-1.8.7-2012.02 :005 > output[2].object_id => 2219989240 ree-1.8.7-2012.02 :006 > output[3].object_id => 2219989240 ree-1.8.7-2012.02 :007 > output[4].object_id => 2219989240 

If you want to create multiple copies of an object, use this

  output = Array.new(5) {[]} #=> [[], [], [], [], []] 

The code

  output.each {|i| puts i.object_id} 

will show you

 1.9.3-p194 :005 > output.each {|i| puts i.object_id} 13417360 13417340 13417320 13417300 13417280 => [[], [], [], [], []] 
+1
source

Source: https://habr.com/ru/post/917067/


All Articles