I want to be able to write a lambda/Proc in my Ruby code, serialize it so that I can write it to disk, and then execute the lambda later. Sort of like...
x
Use sourcify
This will work on Ruby 1.8 or 1.9.
def save_for_later(&block)
block.to_source
end
x = 40
s = save_for_later {|y| x + y }
# => "proc { |y| (x + y) }"
g = eval(s)
# => #
g.call(2)
# => 42
See my other answer for capturing free variables.
Update: Now you can also use the serializable_proc gem, which uses sourcify, and captures local, instance, class, and global variables.