[英]How do I only set a state variable in a Store if it has not already been set?
[英]How do I manipulate a variable that has been set to an object?
我写了一个类似于以下的模块:
module One
class Two
def self.new(planet)
@world = planet
end
def self.hello
"Hello, #{@world}"
end
end
end
我打算用以下方式操作模块:
t = One::Two.new("World")
puts t.hello
然而,显然, self.hello
不t
的范围。 我意识到我可以做以下事情:
t = One::Two
t.new("World")
puts t.hello
以前的方法感觉不对,所以我正在寻找替代方案。
您应该创建一个initialize
方法而不是self.new
来创建一个类的对象。 SomeClass.new
将调用该initialize
方法。
如果要访问实例变量,则应使用实例方法执行此操作。 因此,而不是def self.hello
做def hello
。 如果你想要类方法,你也应该使用类变量。 为此, @some_var
使用@@some_var
而不是@@some_var
。
module One
class Two
# use initialize, not self.new
# the new method is defined for you, it creates your object
# then it calls initialize to set the initial state.
# If you want some initial state set, you define initialize.
#
# By overriding self.new, One::Two.new was returning the planet,
# not an initialized instance of Two.
def initialize(planet)
@world = planet
end
# because One::Two.new now gives us back an instance,
# we can invoke it
def hello
"Hello, #{@world}"
end
end
end
t = One::Two.new 'World'
t.hello # => "Hello, World"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.