我發現了我對Ruby或編程理論或兩者兼有的缺陷。看看這段代碼:Ruby變量(數組)分配誤解(使用推式方法)
#!/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
的輸出是
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
問題答:如何push
到local_ar_2
改變其他兩個陣列?我對局部變量的理解是,一旦創建它們,它們就不應該影響任何其他變量,因爲它們是本地變量。
問題B:如何避免發生這種情況?來自C和Perl,這只是讓我頭腦發熱。
我喜歡你把第一句話的方式,非常簡潔和內容豐富。 – LukeP 2015-04-24 19:42:59