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