如何在Ruby中封送lambda(Proc)?

时间:2020-03-05 18:42:21  来源:igfitidea点击:

Joe Van Dyk问Ruby邮件列表:

Hi,
  
  In Ruby, I guess you can't marshal a lambda/proc object, right?  Is
  that possible in lisp or other languages?
  
  What I was trying to do:
l = lamda { ... }
Bj.submit "/path/to/ruby/program", :stdin => Marshal.dump(l)
So, I'm sending BackgroundJob a lambda object, which contains the
  context/code for what to do.  But, guess that wasn't possible.  I
  ended up marshaling a normal ruby object that contained instructions
  for what to do after the program ran.
  
  Joe

解决方案

回答

尝试ruby2ruby

回答

我们无法封送Lambda或者Proc。这是因为它们都被视为闭包,这意味着它们会在定义它们的内存周围封闭并可以引用它。 (要封送它们,我们必须封送它们在创建时可以访问的所有内存。)

正如Gaius指出的那样,我们可以使用ruby2ruby来获取程序的字符串。也就是说,我们可以封送代表红宝石代码的字符串,然后在以后重新评估它。

回答

如果我们对使用Ruby2Ruby获取Ruby代码的字符串版本感兴趣,则可以使用此线程。

回答

我们也可以只将代码作为字符串输入:

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

然后用eval执行

eval code

这将返回红宝石lamda。

使用%{}格式可对字符串进行转义,但仅在不匹配的花括号上关闭。也就是说,我们可以像这样的"%{[] {}}"嵌套大括号,并且仍然将其括起来。

大多数文本语法突出显示程序都没有意识到这是一个字符串,因此仍会显示常规代码突出显示。