p = Proc.new{ |v| puts v }
p(5) #=> 5
这很好,但如果我想"绑定"v,使其动态更新呢。例如:
p = Proc.new{ ... puts v }
v = 5
p #=> 5
v = 7
p #=> 7
您已经做对了。只需使用调用来执行您的proc:
irb(main):001:0> v= 42
=> 42
irb(main):002:0> p= Proc.new{ puts v }
=> #<Proc:0x422007a8@(irb):2>
irb(main):003:0> p.call
42
=> nil
irb(main):004:0> v= 43
=> 43
irb(main):005:0> p.call
43
=> nil
irb(main):006:0>
在proc之前声明变量。当创建proc时,它将考虑已经声明的任何局部变量。
这是因为变量是在proc之后声明的。
1.9.3p327 :001 > p = Proc.new { puts a }
=> #<Proc:0x9b91e4c@(irb):1>
1.9.3p327 :002 > p.call()
NameError: undefined local variable or method `a' for main:Object
from (irb):1:in `block in irb_binding'
from (irb):2:in `call'
from (irb):2
from /home/chris/.rvm/rubies/ruby-1.9.3-p327/bin/irb:16:in `<main>'
1.9.3p327 :003 > a = 1
=> 1
1.9.3p327 :004 > p.call()
NameError: undefined local variable or method `a' for main:Object
from (irb):1:in `block in irb_binding'
from (irb):4:in `call'
from (irb):4
from /home/chris/.rvm/rubies/ruby-1.9.3-p327/bin/irb:16:in `<main>'
这适用于在proc之前声明的变量。
1.9.3p327 :001 > a = 1
=> 1
1.9.3p327 :002 > p = Proc.new { puts a }
=> #<Proc:0x8cc2d44@(irb):2>
1.9.3p327 :003 > p.call()
1
=> nil
1.9.3p327 :004 > a = 2
=> 2
1.9.3p327 :005 > p.call()
2
=> nil