0

I have two ways I might need to call some code using a block.

Option 1:

foo()

Option 2:

block_function do 
  foo()
end

How do I switch between the two of these at runtime? I really don't want to do the following, because foo() is actually a whole lot of code:

if condition then
    foo()
else
    block_function do 
      foo()
    end
end
4

1 回答 1

1
def condition_or_block_function
  if condition
    yield
  else
    block_function { yield }
  end
end

condition_or_block_function do
  foo() # which is really a lot of code :)
end

或者像其他人建议的那样,将foo()一堆代码变成一个实际的方法,然后写下你在 OP 中写的东西。

@tadman 建议的更通用的版本:

def condition_or_block condition, block_method, *args
  if condition
    yield
  else
    send(block_method, *args) { yield }
  end
end

condition_or_block(some_condition, some_block_yielding_method) do
  foo() # which is really a lot of code :)
end

@Christian Oudard 添加了一条注释,指定了具体问题,可以选择使用 div do...end with Erector 装饰代码块。这提出了另一种方法:

class BlockWrapper
  def initialize(method=nil)
    @method = method
  end
  def decorate
    @method ? send(method) { yield } : yield
  end
end

wrapper = BlockWrapper.new( condition ? nil : :div )

wrapper.decorate do
  #code block
end
于 2012-05-15T18:29:05.767 回答