加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 20:57:58 所属栏目:百科 来源:网络整理
导读:我有很多方法,我称之为: with_this do with_that do and_in_this_context do yield end endend 我记得有一个技巧来递归包装这样的块调用. 我如何编写一个阻止包装的方法? def in_nested_contexts(blk) contexts = [:with_this,:with_that,:and_in_this_con
我有很多方法,我称之为:
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,:and_in_this_context].reverse.inject(blk) {|block,symbol|
    ->{ send symbol,&block }
  }.call
end

如果使用before语句和before语句包装with_this,et al方法,可以看到这一点:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读