When I run the following code, it sets the middle value of each of the
five arrays within square to 1, whereas I would expect it to set only
the middle value of the last array to 1. How can I set only the middle
value of the last array within square?
order = 5
square = []
ary = []
order.times do
0.upto(order-1) do |i|
ary[i] = 0
end
square.push(ary)
end
square[order-1][(order-1)/2] = 1
0.upto(order-1) do |i|
print “\n#{square[i]}”
end
7stud: Thanks for the code suggestions for setting up square as an array
of arrays. Now I need to know how to assign a value to just the middle
element of the last array within square. For reasons unknown to me, my
present code, reproduced below, assigns the value 1 to the middle
element of all five of the arrays within square. Thanks again.
square[order-1][(order-1)/2] = 1
You’re pushing the same array every time and editing the values within
that same array when you’re in the loop. You need to create the array
inside the loop rather than outside it in order to create a different
array every time.
square = []
ary = []
5.times do
square << ary
end
p square #=>[[], [], [], [], []]
ary[0] = ‘hello’
p square #=>[[“hello”], [“hello”], [“hello”], [“hello”], [“hello”]]
square.each do |arr|
puts arr.object_id
end
–output:–
2160289360
2160289360
2160289360
2160289360
2160289360
=====
square = []
5.times do
square << Array.new
end
square.each do |arr|
puts arr.object_id
end
–output:–
2160289740
2160289720
2160289700
2160289680
2160289660
And in fact, you can create a new array with the array literal
syntax:
5.times do
square << []
end
require ‘pp’
order = 5
square = []
1.upto(5) do |i|
ary = [0] * order #[] is the literal array constructor, which
#creates a new array every time it executes
ary[2] = ‘hello’ if i == 5
square << ary
end
pp square
–output:–
[[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, “hello”, 0, 0]]
Joel: Thanks for explaining in plain English. As soon as I put the code
creating ary inside the loop, the program produced the desired results.
I did some more testing in IRB and now I know I was creating multiple
instances of the same object, all with identical object_id.
7stud: Thanks for the code examples.