instance_eval doesn't work with att_accessor?
-
26-05-2021 - |
Pergunta
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?
Solução
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
Outras dicas
Change:
a.instance_eval do
self.b = 2
end
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow