Search code examples
rubyblockproc

How to pass a variable to a Ruby proc that updates dynamically?


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

This works fine, but what if I want to "bind" v so it updates dymanically. For example:

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

Solution

  • You already did it right. Just use call to execute your 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>