[英]Optionally calling a block in ruby
I have two ways I might need to call some code using a block. 我有两种方法可能需要使用一个块来调用一些代码。
Option 1: 选项1:
foo()
Option 2: 选项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: 我真的不想执行以下操作,因为
foo()
实际上是很多代码:
if condition then
foo()
else
block_function do
foo()
end
end
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
Or as others suggested, make the foo()
bunch of code an actual method and write what you wrote in the OP. 或者像其他人所建议的那样,使
foo()
一堆代码成为实际方法,并编写您在OP中编写的内容。
More generic version as @tadman suggests: @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 added a comment specifying the specific problem, optionally decorating a code block with div do...end with Erector. @Christian Oudard添加了说明特定问题的注释,可以选择使用div do ... end与Erector装饰代码块。 This suggests another approach:
这表明了另一种方法:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.