簡體   English   中英

attr_accessor沒有更新值

[英]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_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

這沒有發生 - 測試失敗:

Failures:

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

       expected: 2
            got: 1

       (compared using ==)

這不是屬性訪問器應該如何工作? 我錯過了什么?

您只是定義局部變量ab

您想要的是為實例變量ab設置新值。 以下是如何做到這一點:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM