我正在尝试处理 Ruby 中一个非常奇怪(至少对我而言)的情况。我的代码如下:
class ScopeTest
attr_accessor :flag
def flagtest
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
if flag == 1
flag = 0
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
self.flag = 0
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
flagtest
else
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
end
end
end
st = ScopeTest.new
st.flag = 1
st.flagtest
输出如下:
SELF: 1
INST: 1
SELF: 1
INST: 0
SELF: 0
INST: 0
SELF: 0
INST: 0
SELF: 0
INST:
奇怪的是该flag
变量是nil
我最后一次打印它(在内部else
)但0
在此之前(在if...else
flagtest 方法之前)?
当我删除几行代码时,一切似乎恢复正常,如下代码:
class ScopeTest
attr_accessor :flag
def flagtest
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
if flag == 1
self.flag = 0
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
flagtest
else
puts "SELF: " + self.flag.to_s
puts "INST: " + flag.to_s
end
end
end
st = ScopeTest.new
st.flag = 1
st.flagtest
给出以下输出:
SELF: 1
INST: 1
SELF: 0
INST: 0
SELF: 0
INST: 0
SELF: 0
INST: 0
关于发生什么以及为什么发生的任何线索?