红宝石 1.9
我突然意识到我不明白如何在 Ruby 中定义和初始化实例变量。它只能在某个特定的范围内使用class
,并且根本无法从类中访问,因此attr_accessor
或者attr_reader
不是我需要的。
class MyClass
#how do I initialize it?
@my_var = 'some value'
def method1
#I need to do something with @my_var
puts @my_var
end
def method2
#I need to do something with @my_var
puts @my_var
end
end
a = MyClass.new
a.method1 #empty
a.method2 #empty
所以我发现还有另一种方法可以做到
class MyClass
#is this the only way to do it?
def initialize
@my_var = 555
end
def method1
#I need to do something with @my_var
puts @my_var
end
def method2
#I need to do something with @my_var
puts @my_var
end
end
a = MyClass.new
a.method1 #555; it's ok
a.method2 #555; it's ok
那么,第二种方法是正确的吗?