假设我有with_foo一个带块的函数,并将它包装在一段代码中,比如
with_foo do
puts "hello!"
end
Run Code Online (Sandbox Code Playgroud)
现在我想使包装有条件,如
if do_with_foo?
with_foo do
puts "hello!"
end
else
puts "hello!" # without foo
end
Run Code Online (Sandbox Code Playgroud)
有没有办法写这个更短/更优雅,意味着不必重复代码puts "hello!"?
如果你愿意用块指定参数,那么它是可能的.
鉴于with foo以上,你可以写这样的片段:
whatever = proc {puts "hello"}
#build a proc object with a block
if do_with_foo?
with_foo &whatever
#pass it to with_foo
else
whatever.call
#normally call it
end
Run Code Online (Sandbox Code Playgroud)