今天看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对象。
例子

  1. def test1 b
  2.     eval "puts a" ,b
  3.     eval "a=200",b
  4.     eval "puts a" ,b
  5.     eval "puts c",test3
  6.     eval "puts d",TOPLEVEL_BINDING
  7. end
  8.  
  9.  
  10. def test2 
  11.   a=100
  12.   test1 binding
  13. end
  14.  
  15.  
  16. def test3 
  17.   c=300
  18.   binding
  19. end
  20.  
  21. d = 400
  22.  
  23. test2
  24. #will print
  25. #100
  26. #200
  27. #300
  28. #400
  29. def add_method2class b
  30.     eval "class_eval \"def hello;puts 'hello binding';end\"",b
  31. end
  32.  
  33.  
  34. class Test
  35.     add_method2class binding
  36. end
  37.  
  38.  
  39. t = Test.new
  40. t.hello
  41. #will print
  42. #hello 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]

Related posts for the current post: