Search code examples
rubyblockinstance-eval

instance_eval doesn't work with att_accessor?


Can anybody say me, why that isn't working:

class A
  attr_accessor :b
end

a = A.new
a.instance_eval do
  b = 2
end

a.b
=> nil

What is wrong i'm doing?


Solution

  • The culprit lies in this part of the code:

    a.instance_eval do
      b = 2
    end
    

    Although b = 2 is evaluated in the context of your instance, it doesn't call the setter. Instead it just creates a new local variable called b in the current scope. To call the setter, you have to further clarify your code to resolve the ambiguity:

    a.instance_eval do
      self.b = 2
    end