I’m trying to figure out why the following codes doesn’t return the same result:
CODE 1
p0 = "hello"
a = []
b = p0
1.upto(5) do |i|
b.insert(2,"B")
a.push b
end
a => ["heBBBBBllo", "heBBBBBllo", "heBBBBBllo", "heBBBBBllo", "heBBBBBllo"]
CODE 2
p0 = "hello"
a = []
b = p0
1.upto(5) do |i|
b.insert(2,"B")
a.push b.inspect
end
a => ["\"heBllo\"", "\"heBBllo\"", "\"heBBBllo\"", "\"heBBBBllo\"", "\"heBBBBBllo\""]
What I need is the Code 2’s result, but I don’t need the escaped char like the inspect method does.
Honestly, I really don’t understand why with the inspect method works, and why in the code 1 doesn’t.
It seems like that in code 1, “b” is used as a pointer, and every time it’s updated, all the “linked”-b are updated.
Any clue??
thank you in advance.
Correct! In the first case, you’re pushing
binto the array five times, so the result is thatacontains five pointers tob. In the second case you’re pushingb.inspect– which is a different object fromb.The easiest way to fix your first example would be to call
a.push b.dupinstead, which creates a duplicate ofbwhich won’t be affected by future changes tob.