今天看Ruby Cookbook发现了这里面对binding的解释是目前看到的比较通俗易懂的了。
A Binding object is a bookmark of the Ruby interpreter’s state. It tracks the values of any local variables you have defined, whether you are inside a class or method definition, and so on.
Once you have a Binding object, you can pass it into eval to run code in the same context as when you created the Binding. All the local variables you had back then will be available. If you called Kernel#binding within a class definition, you’ll also be able to define new methods of that class, and set class and instance variables.
binding方法会返回一个Binding对象的实例,它记载了创建它的时候的环境,比如当时的变量等。然后你可以把这个binding变量传给方法等,它经常作为eval的第二个参数,这样eval里面就不会因为找不到变量出错了。
中文信息,请参照这两个网址
http://cn.ce-lab.net/man/stdlib_function.html
http://cn.ce-lab.net/man/built-in-class/class_object_binding.html
另外,Ruby还提供了内部常数TOPLEVEL_BINDING以用作顶层的Binding对象。
例子
结果
C:\jruby\bin>jruby b.rb
100
200
300
400
hello binding
C:\jruby\bin>jruby -v
ruby 1.8.5 (2007-06-07 rev 3841) [x86-jruby1.0]
RSS feed for comments on this post · TrackBack URI
Leave a reply