RUBY 实例变量在调用另一个方法时被重新初始化
RUBY instance variable is reinitialized when calling another method
为什么实例变量@my_instance return nil 甚至认为它在my_method 中被设置为0 ?
attr_accessor应该让我读写实例吧?
做这样的事情的正确方法是什么?
谢谢。
class Myclass
attr_accessor :my_instance
def initialize
@my_instance
end
def called_method
puts "this is my instance value #{my_instance} "
end
def my_method
my_instance = 0
puts "i set my instance to be #{my_instance}"
called_method
end
end
a = Myclass.new
a.my_method
called_method return nil 当我期望 0
what would be the right way to do something like this ?
my_instance = 0
这会创建一个局部变量,而不是调用您的 setter。提示 ruby 你想调用方法:
self.my_instance = 0
或者直接设置实例变量:
@my_instance = 0
为什么实例变量@my_instance return nil 甚至认为它在my_method 中被设置为0 ?
attr_accessor应该让我读写实例吧?
做这样的事情的正确方法是什么?
谢谢。
class Myclass
attr_accessor :my_instance
def initialize
@my_instance
end
def called_method
puts "this is my instance value #{my_instance} "
end
def my_method
my_instance = 0
puts "i set my instance to be #{my_instance}"
called_method
end
end
a = Myclass.new
a.my_method
called_method return nil 当我期望 0
what would be the right way to do something like this ?
my_instance = 0
这会创建一个局部变量,而不是调用您的 setter。提示 ruby 你想调用方法:
self.my_instance = 0
或者直接设置实例变量:
@my_instance = 0