模块中的实例变量? [英] Instance variables in modules?
本文介绍了模块中的实例变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使无法创建模块的实例,怎么可能在模块中包含实例变量?以下模块Stacklike
中@stack
的用途是什么?
How is it possible that I can have instance variables in a module even though I cannot create an instance of the module? What would be the purpose of @stack
in module Stacklike
below?
module Stacklike
def stack
@stack ||= []
end
end
推荐答案
将实例变量视为在包含您的模块的任何类中都将存在的东西,并且事情变得更有意义了:
Think of the instance variable as something which will exist in any class that includes your module, and things make a bit more sense:
module Stacklike
def stack
@stack ||= []
end
def add_to_stack(obj)
stack.push(obj)
end
def take_from_stack
stack.pop
end
end
class ClownStack
include Stacklike
def size
@stack.length
end
end
cs = ClownStack.new
cs.add_to_stack(1)
puts cs.size
将输出"1"
这篇关于模块中的实例变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文