1

I'm new to ruby so I'm clearly misunderstanding something. I intended to create an array of size 2, where each element is itself an array, then push items to one or the other sub-array:

#!/usr/bin/env ruby
arr = Array.new(2, Array.new)

puts 'default, no entries:'
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
puts ''

puts 'adding "kitty" to arr[0]:'
arr[0].push('kitty') # add an element to the sub-array at arr[0]
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }
puts ''

puts 'adding "doggy" to arr[1]:'
arr[1].push('doggy') # add an element to the sub-array at arr[1]
arr.each_with_index { |a, i| puts 'arr[' + i.to_s + '] = ' + a.to_s }

output:

default, no entries:
arr[0] = []
arr[1] = []

adding "kitty" to arr[0]:
arr[0] = ["kitty"]
arr[1] = ["kitty"]

adding "doggy" to arr[1]:
arr[0] = ["kitty", "doggy"]
arr[1] = ["kitty", "doggy"]

I would expect arr[0].push() to add the element at arr[0][0], is that wrong?

2 Answers 2

4

arr = Array.new(2, Array.new) assigns the same array to both of the new objects.

If you use a block form instead, you'll get two separate arrays as you expect:

arr = Array.new(2) { Array.new }
Sign up to request clarification or add additional context in comments.

1 Comment

You can observe this with arr.map(&:object_id) #=> [70190130252680, 70190130252680]
0

It seems that you're creating an array, where each element is a reference to the one same array object:

arr = Array.new(2, Array.new)
#=> [[], []]
arr[0].push(1)
#=> [1]
arr
#=> [[1], [1]]

Instead, do

arr = [[],[]]
#=> [[], []]
arr[0].push(1)
#=> [1]
arr
#=> [[1], []]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.