1
p = Proc.new{ |v| puts v }
p(5) #=> 5

这很好用,但是如果我想“绑定” v 让它动态更新怎么办。例如:

p = Proc.new{ ... puts v }
v = 5
p #=> 5
v = 7
p #=> 7
4

2 回答 2

3

你已经做对了。只需使用 call 来执行你的过程:

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> 
于 2013-02-22T13:19:12.090 回答
1

在 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
于 2013-02-22T13:19:54.107 回答