how to serialize a proc/lambda in Ruby
A friend asked on twitter if we could retrieve the Ruby code as a string from a Proc or Lambda with something for example: puts (lambda {1==1}).code –> “1==1″ see his original tweet.
It can probably be done with some Ruby2Ruby magic, here’s my 15 minutes attempt. First you need to install Ruby2Ruby from http://seattlerb.rubyforge.org/ruby2ruby/
l = lambda { |i| i + 1 }
def xlate(proc)
(c = Class.new).class_eval { define_method :proc, proc }
Ruby2Ruby.translate(c, :proc)
end
irb(main):009:0> xlate(l)
"def proc(i)\n (i + 1)\nend"
Now, maybe a bit of regexp on the output and that’s probably close to what you need!
Enjoy!
