How do I marshal a lambda (Proc) in Ruby? How do I marshal a lambda (Proc) in Ruby? ruby ruby

How do I marshal a lambda (Proc) in Ruby?


You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.)

As Gaius pointed out though, you can use ruby2ruby to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later.


you could also just enter your code as a string:

code = %{    lambda {"hello ruby code".split(" ").each{|e| puts e + "!"}}}

then execute it with eval

eval code

which will return a ruby lamda.

using the %{} format escapes a string, but only closes on an unmatched brace. i.e. you can nest braces like this %{ [] {} } and it's still enclosed.

most text syntax highlighters don't realize this is a string, so still display regular code highlighting.


If you're interested in getting a string version of Ruby code using Ruby2Ruby, you might like this thread.