我如何从佣金任务中提前返回? [英] How do I return early from a rake task?
问题描述
我有一个 rake 任务,我在开始时做了一些检查,如果其中一个检查失败,我想从 rake 任务中尽早返回,我不想执行任何剩余的代码.
I have a rake task where I do some checks at the beginning, if one of the checks fails I would like to return early from the rake task, I don't want to execute any of the remaining code.
我认为解决方案是在我想从代码返回的地方放置一个返回,但我收到以下错误
I thought the solution would be to place a return where I wanted to return from the code but I get the following error
unexpected return
推荐答案
Rake 任务基本上是一个块.一个块,除了 lambdas,不支持 return,但你可以使用 next
跳到下一个语句,这在 rake 任务中与在方法中使用 return 具有相同的效果.
A Rake task is basically a block. A block, except lambdas, doesn't support return but you can skip to the next statement using next
which in a rake task has the same effect of using return in a method.
task :foo do
puts "printed"
next
puts "never printed"
end
或者您可以移动方法中的代码并在方法中使用返回.
Or you can move the code in a method and use return in the method.
task :foo do
do_something
end
def do_something
puts "startd"
return
puts "end"
end
我更喜欢第二个选择.
这篇关于我如何从佣金任务中提前返回?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!