需要有关绑定对象的帮助

时间:2013-03-26 06:27:56

标签: ruby binding ruby-2.0

来自Binding object

  

Binding类的对象将执行上下文封装在代码中的某个特定位置,并保留此上下文以供将来使用。变量, 方法,self的值以及可能在此上下文中可以访问的迭代器块都保留 。可以使用Kernel#binding创建绑定对象,并且可用于Kernel#set_trace_func 的回调。

任何人都可以帮助我通过上面每条粗线的单个例子来理解这个事实吗?

1 个答案:

答案 0 :(得分:2)

<强>方法:

x = eval("foo", binding) rescue "foo undefined"
puts x

def foo; "foo"; end

puts eval("foo", binding)

输出:

foo undefined
foo

self的价值:

puts eval("self", binding)
class Foo
  def eval_self
    eval("self", binding)
  end
end
puts Foo.new.eval_self

输出:

main
#<Foo:0x10c5a3018>

迭代器块:

block = eval("yield", binding) rescue "no iterator block"
puts block

def block
  eval("yield", binding)
end
puts block { "iterator block" }

输出:

no iterator block
iterator block

<强>内核#set_trace_func:

class Test
  def test
    a = 1
  end
end

set_trace_func proc { |event, file, line, id, binding, classname|
  puts eval("self", binding)
}
t = Test.new
t.test

输出:

main
Test
#<Test:0x10204cb28>
#<Test:0x10204cb28>
Test
main
#<Test:0x10204cb28>
#<Test:0x10204cb28>
#<Test:0x10204cb28>
main
main
main

您可以在documentation中详细了解Kernel#set_trace_func