【问题标题】:How to pass a variable to a Ruby proc that updates dynamically?如何将变量传递给动态更新的 Ruby proc?
【发布时间】:2013-02-22 13:15:17
【问题描述】:
p = Proc.new{ |v| puts v }
p(5) #=> 5

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

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

【问题讨论】:

    标签: ruby block proc


    【解决方案1】:

    你已经做对了。只需使用 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> 
    

    【讨论】:

      【解决方案2】:

      在 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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多