以下是代码:
class Something
attr_accessor :x
def initialize(x)
@x = x
end
def get_x
x
end
end
something = Something.new(5)
something.get_x # => 5
如果x
只是get_x
方法中的局部变量,为什么解释器返回5?感谢
答案 0 :(得分:5)
x
也是一种方法。 attr_accessor :x
为您的班级添加了x=
和x
。因此,get_x调用x
方法,并返回@x
的值。有关详细信息,请参阅http://www.rubyist.net/~slagell/ruby/accessors.html。
答案 1 :(得分:4)
attr_accessor :x
为您添加了两种方法:
def x=(val)
@x = val
end
def x
@x
end
如果你添加了get_x
方法,那么你实际上并不需要attr_accessor
getter。
<强> UPD 强>
所以问题是
class Something
attr_accessor :x
def initialize(x)
@x = x
end
def set_x=(new)
x = new
end
end
为什么x = new
不会调用默认的x
setter:因为默认的x
setter是一个实例方法,所以你可以为一个对象(Something实例)调用它,但不能在你的类中调用它就像你尝试一样。
答案 2 :(得分:2)
attr_accessor
定义了在x
中调用的方法x=
(和setter get_x
)。
>> something.methods.grep /^x/
=> [:x, :x=]