我无法理解为什么我的代码不起作用。
class Container
module Actions
@instance_variable = 0;
def action1
return @instance_variable # no error, but doesn't return 0! What can be done ?
end
end
include Actions
end
Container.new.action1()
我觉得有一个简单的答案。
答案 0 :(得分:2)
您应该将它放在初始化函数中:
class Container
module Actions
def initialize
@instance_variable = 0;
end
def action1
return @instance_variable # no error, but doesn't return 0! What can be done ?
end
end
include Actions
end
puts Container.new.action1().inspect ## 0
另一种不太合适的方法是在未设置实例的情况下给出默认值:
class Container
module Actions
def action1
@instance_variable ||= 0
return @instance_variable # no error, but doesn't return 0! What can be done ?
end
end
include Actions
end
答案 1 :(得分:0)
您的代码无效,因为@instance_variable
是Container::Actions
模块对象的实例。通过instance_variables
检查:
Container::Actions.instance_variables
# => [:@instance_variable]
它与你在课堂上定义的相同(不在initialize
中):
class A
@var = 42
end
A.instance_variables
# => [:@var]
因此,如果您真的想使用Container::Actions
的实例变量,可以使用instance_variable_get
:
class Container
module Actions
@instance_variable = 0;
return Actions.instance_variable_get :@instance_variable
end
end
include Actions
end
Container.new.action1()