代码之家  ›  专栏  ›  技术社区  ›  Exp HP

使用变量的当前值创建过程

  •  2
  • Exp HP  · 技术社区  · 15 年前

    class Foo              # This is a class I cannot
      def setmyproc(&code) # safely edit.
        @prc = Proc.new    # Due to it being in a
      end                  # frustratingly complex
      def callmyproc()     # hierarchy, I don't
        @prc.call          # even know how to reopen
      end                  # it. Consider this class
    end                    # set in stone.
    

    当我尝试迭代并生成这些对象的数组时,我遇到了一个问题。我希望用一个不同的值来代替 i

    $bar = []
    for i in (0..15)
      $bar[i] = Foo.new
      $bar[i].setmyproc { puts i }
    end
    
    $bar[3].callmyproc # expected to print 3
    $bar[6].callmyproc # expected to print 6
    

    输出

      15
      15

    在循环中我可以做些什么来保留

    3 回复  |  直到 15 年前
        1
  •  3
  •   Adrian    15 年前

    $bar = []
    (0..15).each do |i|
      $bar[i] = Foo.new
      $bar[i].setmyproc { puts i }
    end
    
    $bar[3].callmyproc # prints 3
    $bar[6].callmyproc # prints 6
    

    $bar = []
    for i in (0..15)
      ->(x) do
        $bar[x] = Foo.new
        $bar[x].setmyproc { puts x }
      end.(i)
    end
    
    $bar[3].callmyproc # prints 3
    $bar[6].callmyproc # prints 6
    
        2
  •  2
  •   Bryan Ash    15 年前

    传递到$bar数组中每个Foo的块绑定到同一个变量 i callmyproc 的当前值 在原来的范围内使用。

    $bar[3].callmyproc
    => 15
    $bar[6].callmyproc
    => 15
    
    i = 42
    
    $bar[3].callmyproc
    => 42
    $bar[6].callmyproc
    => 42
    

    您需要向每个进程发送不同的对象:

    0.upto(15) do |i|
      $bar[i] = Foo.new
      $bar[i].setmyproc { i.to_i }
    end
    
    $bar[3].callmyproc
     => 3 
    $bar[6].callmyproc
     => 6 
    
        3
  •  1
  •   Matt Briggs    15 年前

    实际情况是,当您存储proc时,每个proc都带有一个对n的引用。即使您超出for循环的范围,对n的引用仍然存在,并且每次执行过程时,它们都会打印n的最终值。这里的问题是,每个迭代都不在自己的范围内。

    阿德里安建议做的是把for循环换成range.each block。不同之处在于,每个迭代都有自己的作用域,这就是绑定到proc的范围

    $bar = []
    (0..15).each do |i|
      #each i in here is local for this block
      $bar[i] = Foo.new
      $bar[i].setmyproc { puts i }
    end
    

    推荐文章