While migrating code from ruby 1.8.6 to 2.0 I noticed that the behaviour of eval with bindings has changed. I did not find any information about that and the documentation of those methods has not changed its wording.

object = Math
binding = object.__send__(:binding)
puts eval("self", binding)
puts eval("sin(0.2)", binding)

gives in irb1.8:

> Math
> 0.1986…

and in irb2.0:

> main
> NoMethodError

I get the same when using the new binding.eval("self")

What is the underlying change, and how can I implement the previous behavior in Ruby 2.0?

有帮助吗?

解决方案

Compare the following, both from Ruby 2.0:

 b = Math.__send__(:binding)
 b.eval("self")
 => main

 b = Math.instance_eval { binding }
 b.eval("self")
 => Math

 # or equivalently...
 b = Math.instance_eval("binding")
 b.eval("self")
 => Math

The documentation for Kernel#binding says it "describes the variable and method bindings at the point of call". I think that accurately describes the behavior you are seeing with Math.__send__(:binding). The Binding object you get back retains the value of self at the point of call.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top