~/Chapter8ReflectionandMetaprogramming$ cat -n bindingsAndEval.rb 1 class Demo 2 def initialize(n) 3 @secret = n 4 end 5 def getBinding 6 return binding() 7 end 8 end 9 10 k1 = Demo.new(99) 11 b1 = k1.getBinding 12 k2 = Demo.new(-3) 13 b2 = k2.getBinding 14 15 puts eval("@secret", b1) #=> 99 16 puts eval("@secret", b2) #=> -3 17 puts eval("@secret") #=> nilEjecución:
~/Chapter8ReflectionandMetaprogramming$ ruby bindingsAndEval.rb 99 -3 nil
def fred(param) proc {} end def multiplier(n) lambda do |*arr| arr.collect { |i| i*n } end end b = fred(99) puts eval("param", b.binding) #=> 99 puts "********************************" doubler = multiplier(2) puts doubler[1, 2, 3] # 2 4 6 puts "********************************" eval("n = 3", doubler.binding) puts doubler.call(1, 2, 3) # 3 6 9 puts "********************************" eval("n = 5", doubler) puts doubler.call(1, 2, 3) # 5 10 15
ejecución:
~/Chapter8ReflectionandMetaprogramming$ ruby procsAndBindings.rb 99 ******************************** 2 4 6 ******************************** 3 6 9 ******************************** 5 10 15
Casiano Rodriguez León 2015-01-07