I have discovered a flaw in my understanding of ruby or programming theory or both. Look At This Code:
#!/usr/bin/ruby -w
@instance_ar = [1,2,3,4]
local_ar = @instance_ar
local_ar_2 = local_ar
###
irrelevant_local_ar = [5,6,7,8]
###
for i in irrelevant_local_ar
local_ar_2.push(i)
end
count = 0
for i in local_ar_2
puts "local_ar_2 value: #{i} and local_ar value: #{local_ar[count]} and @instance_ar value: #{@instance_ar[count]}\n"
count += 1
end
The output of that is
local_ar_2 value: 1 and local_ar value: 1 and @instance_ar value: 1 local_ar_2 value: 2 and local_ar value: 2 and @instance_ar value: 2 local_ar_2 value: 3 and local_ar value: 3 and @instance_ar value: 3 local_ar_2 value: 4 and local_ar value: 4 and @instance_ar value: 4 local_ar_2 value: 5 and local_ar value: 5 and @instance_ar value: 5 local_ar_2 value: 6 and local_ar value: 6 and @instance_ar value: 6 local_ar_2 value: 7 and local_ar value: 7 and @instance_ar value: 7 local_ar_2 value: 8 and local_ar value: 8 and @instance_ar value: 8
Question A: How in the world does push
to local_ar_2
change 2 other arrays? My understanding of local variables was that once they were created, they should not affect any other variables, being that they were local.
Question B: How can I avoid things like this from happening?
Coming from C, Perl this is just blowing my mind.