0

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?

freeze
  • 546
  • 6
  • 16

2 Answers2

6

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
Holger Just
  • 52,918
  • 14
  • 115
  • 123
0

Change:

a.instance_eval do
  self.b = 2
end
Dmitry Reznik
  • 6,812
  • 2
  • 32
  • 27