Ruby:引用当前正在执行的块

时间:2017-06-12 15:52:05

标签: ruby

有没有办法在Ruby中引用当前正在执行的块进行一次性递归?例如,执行" deep"合并哈希:

hash1.merge(hash2) do |k,o,v|
  (o.is_a?(Hash) && v.is_a?(Hash)) ? o.merge(v, &CURRENT_BLOCK) : v
end

我知道我可以在外部定义块并引用它,我只是想知道它是否可以就地进行。

1 个答案:

答案 0 :(得分:1)

I think you're looking for some sort of Y combinator in Ruby. I don't believe this is possible to do in Ruby with ordinary blocks, but you can do something similar with lambdas:

lambda { |x| p x += 1; redo }[0]

Alternatively, you could implement a Y combinator generator using methods or lambdas, as shown on this RosettaCode page.