簡體   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