简体   繁体   English

attr_accessor没有更新值

[英]attr_accessor not updating value

I have a class with attribute accessors: 我有一个带属性访问器的类:

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

I think that after calling update_values , a and b should retain their new values: 我认为在调用update_valuesab应该保留它们的新值:

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

This is not happening - the test fails: 这没有发生 - 测试失败:

Failures:

  1) MyClass should set a and b
     Failure/Error: expect(@thing.a).to eq 2

       expected: 2
            got: 1

       (compared using ==)

Isn't this how attribute accessors should work? 这不是属性访问器应该如何工作? What am I missing? 我错过了什么?

You are just defining local variables a and b . 您只是定义局部变量ab

What you want instead, is to set new values for instance variables a and b . 您想要的是为实例变量ab设置新值。 Here is how you can do that: 以下是如何做到这一点:

def update_values options
  self.a = options[:a] # or @a = options[:a]
  self.b = options[:b] # or @b = options[:b]
end

Now: 现在:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM