I’m experiencing some unexpected behavior with instance_eval
in Ruby 3.3.0 and am hoping to gain some insights or find out if anyone else has encountered something similar.
Here’s the code snippet that demonstrates the issue:
puts "Ruby ver.#{RUBY_VERSION}"
class A
attr_accessor :name, :gagaga
end
a = A.new
a.name = "Hello World! from name"
p a.name # Expected: "Hello World! from name", Actual: "Hello World! from name"
p a.instance_eval("self.name") # Expected: "Hello World! from name", Actual: "Hello World! from name"
p a.instance_eval("name") # Expected: "Hello World! from name", Actual: nil
name = "name"
p a.instance_eval(name) # Expected: "Hello World! from name", Actual: "name"
attr_name = "name"
p a.instance_eval(attr_name) # Expected: "Hello World! from name", Actual: "name"
a.gagaga = "Hello World! from gagaga"
p a.gagaga # Expected: "Hello World! from gagaga", Actual: "Hello World! from gagaga"
p a.instance_eval("self.gagaga") # Expected: "Hello World! from gagaga", Actual: "Hello World! from gagaga"
p a.instance_eval("gagaga") # Expected: "Hello World! from gagaga", Actual: "Hello World! from gagaga"
name = "gagaga"
p a.instance_eval(name) # Expected: "Hello World! from gagaga", Actual: "Hello World! from gagaga"
attr_name = "gagaga"
p a.instance_eval(attr_name) # Expected: "Hello World! from gagaga", Actual: "Hello World! from gagaga"
p a.instance_eval("name") # Expected: "Hello World! from gagaga", Actual: "gagaga"
Here’s the actual outputs.
Ruby ver.3.3.0
"Hello World! from name"
"Hello World! from name"
nil
"name"
"name"
"Hello World! from gagaga"
"Hello World! from gagaga"
"Hello World! from gagaga"
"Hello World! from gagaga"
"Hello World! from gagaga"
"gagaga"
I’m puzzled by some outcomes:
-
a.instance_eval("name")
returnsnil
, contrary to expectations. - Using variables
name
andattr_name
with the value"name"
ina.instance_eval(name)
anda.instance_eval(attr_name)
returns the string"name"
instead of the value of@name
. - The final call
a.instance_eval("name")
unexpectedly returns"gagaga"
, the value of a different attribute.
These results seem inconsistent, particularly the nil
return and the unexpected string return values in place of the actual attribute values. I’m curious if this is a known issue, a feature of how instance_eval
interprets strings, or perhaps a misunderstanding on my part regarding its usage.
Any insights, explanations, or suggestions for further reading would be greatly appreciated.
Thank you for your help.