Ruby - 从 IF 块退出
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7825093/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby - exit from IF block
提问by Vladimir Tsukanov
In IF block i need to check if some condition true and if it does, exit from block.
在 IF 块中,我需要检查某些条件是否为真,如果为真,则从块中退出。
#something like this
if 1 == 1
return if some_object && some_object.property
puts 'hello'
end
How can i do it?
我该怎么做?
回答by tadman
You can't break out of an iflike that. What you can do is add a sub-clause to it:
你不能摆脱if这样的。您可以做的是为其添加一个子条款:
if (cond1)
unless (cond2)
# ...
end
end
If you're having problems with your logic being too nested and you need a way to flatten it out better, maybe what you want to do is compute a variable before hand and then only dive in if you need to:
如果您的逻辑过于嵌套而遇到问题,并且您需要一种更好地将其展平的方法,也许您想要做的是事先计算一个变量,然后仅在需要时才深入研究:
will_do_stuff = cond1
will_do_stuff &&= !(some_object && some_object.property)
if (will_do_stuff)
# ...
end
There's a number of ways to avoid having a deeply nested structure without having to breakit.
有很多方法可以避免深度嵌套的结构,而不必这样break做。
回答by coreyward
Use care in choosing the words you associate with things. Because Ruby has blocks, I'm not sure whether you're under the impression that a conditional statement is a block. You can't, for example, do the following:
在选择与事物相关的词时要小心。因为 Ruby 有块,我不确定您是否认为条件语句是块。例如,您不能执行以下操作:
# will NOT work:
block = Proc.new { puts "Hello, world." }
if true then block
If you need to have a nested conditional, you can do just that without complicating things any:
如果您需要嵌套条件,您可以做到这一点,而不会使任何事情复杂化:
if condition_one?
if condition_two?
# do some stuff
end
else
# do something else
end

