繁体   English   中英

在按名称接受块的方法调用中包装块

[英]Wrapping a block in method calls that accept blocks by name

我有很多方法,我称之为:

with_this do
  with_that do
    and_in_this_context do
      yield
    end
  end
end

我记得有一个技巧来递归包装这样的块调用。 我如何编写一个阻止包装的方法?

def in_nested_contexts(&blk)
  contexts = [:with_this, :with_that, :and_in_this_context]
  # ... magic probably involving inject
end

你确实可以使用inject来创建嵌套的lambdas或procs,你可以在最后调用它们。 你需要你的给定块作为嵌套的内部,所以你反转你的数组并使用该块作为初始值,然后将每个连续函数包装在inject的结果周围:

def in_nested_contexts(&blk)
  [:with_this, :with_that, :and_in_this_context].reverse.inject(blk) {|block, symbol|
    ->{ send symbol, &block }
  }.call
end

如果你换你with_this等方法之前和之后puts语句,你可以在行动中看到这一点:

in_nested_contexts { puts "hello, world" }
#=> 
  with_this start
  with_that start
  context start
  hello, world
  context end
  with_that end
  with_this end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM