Reputation: 27
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?
Upvotes: 1
Views: 172
Reputation: 124419
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 }
Upvotes: 4
Reputation: 20786
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], []]
Upvotes: 0