Ruby – 实例方法:为什么我可以在没有self的情况下使用getter,
发布时间:2020-12-17 03:40:39 所属栏目:百科 来源:网络整理
导读:我一直在使用 Ruby.现在我要深入挖掘,找到我所有问题的所有答案. 我希望我能在这里找到答案.所以这是我在下面的代码中的问题: class Game attr_accessor :in_progress def initialize @in_progress = false end def start! # debug info puts self.inspect
我一直在使用
Ruby.现在我要深入挖掘,找到我所有问题的所有答案.
我希望我能在这里找到答案.所以这是我在下面的代码中的问题: class Game attr_accessor :in_progress def initialize @in_progress = false end def start! # debug info puts self.inspect # => #<Game:0x8f616f4 @in_progress=false> puts self.class.instance_methods(false) # => [:in_progress,:in_progress=,:start!] puts self.instance_variables # => [:@in_progress] puts self.respond_to?("in_progress=") # => true puts in_progress # => true - getter works without self # main quesion in_progress = true # Why setter doesn't work without self? # self.in_progress = true # this would work and set @in_progress to true becase setter called # @in_progress = true # this would work as well because we set instance variable to true directly end end g = Game.new g.start! puts g.in_progress # => false - setter in start! method didn't work 我们在这里有什么: >使用@in_progress变量的getter和setter的类游戏 我读到了Ruby中的方法查找(向右移动一步到接收器的类中,然后向上移动祖先链,直到找到方法.) 提前致谢! 解决方法
因为您正在为函数中的局部变量in_progress赋值,而不是实例变量. getter有效,因为Ruby会查询start的本地命名空间!对于in_progress的函数,它将找不到它,然后它将查询实例命名空间,它将找到一个名为in_progress的方法并将其调用.
Ruby解释器无法确定是否要在本地in_progress或实例变量中分配true值,因此规则是在本地分配(在start中的当前命名空间!). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |