[英]attr_accessor not updating value
我有一个带属性访问器的类:
class MyClass
attr_accessor :a, :b
def initialize
@a = 1
@b = 2
end
def update_values options
a = options[:a]
b = options[:b]
end
end
我认为在调用update_values
, a
和b
应该保留它们的新值:
describe MyClass do
before do
@thing = MyClass.new
end
it 'should set a and b' do
expect(@thing.a).to eq 1
expect(@thing.b).to eq 2
@thing.update_values a: 2, b: 5
expect(@thing.a).to eq 2
expect(@thing.b).to eq 5
end
end
这没有发生 - 测试失败:
Failures:
1) MyClass should set a and b
Failure/Error: expect(@thing.a).to eq 2
expected: 2
got: 1
(compared using ==)
这不是属性访问器应该如何工作? 我错过了什么?
您只是定义局部变量a
和b
。
您想要的是为实例变量a
和b
设置新值。 以下是如何做到这一点:
def update_values options
self.a = options[:a] # or @a = options[:a]
self.b = options[:b] # or @b = options[:b]
end
现在:
foo = MyClass.new
#=> #<MyClass:0x007f83eac30300 @a=1, @b=2>
foo.update_values(a: 2, b: 3)
foo #=>#<MyClass:0x007f83eac30300 @a=2, @b=3>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.