Question

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?

Was it helpful?

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

OTHER TIPS

Change:

a.instance_eval do
  self.b = 2
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top