Ruby on Rails 中是否有 if(没有 else)语句的简写?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10339149/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 05:04:23  来源:igfitidea点击:

Is there a shorthand if (without else) statement in Ruby on Rails?

ruby

提问by Goalie

I know there is a shorthand one-line if/else statement in Ruby:

我知道 Ruby 中有一个简写的单行 if/else 语句:

a ? b : c

Is there one for just a single ifstatement? Instead of writing this:

有没有一个只针对一个if语句的?而不是写这个:

if a
  # do something
end

Is there a shorthand version of this?

这个有简写版本吗?

回答by Sergio Tulentsev

You can use post conditions (don't mind the name, it will be evaluated beforethe code. And do_somethingwill only be executed if condition evaluates to truthy value (i.e. not nilor false)).

您可以使用后置条件(不要介意名称,它将在代码之前进行评估。并且do_something只有在条件评估为真值(即不是nilfalse)时才会执行)。

do_something if a

回答by Charles Caldwell

do_something if a

This will first evaluate the ifcondition (in this case a) and if it is true(or in the case of a, not falseor nil) it will execute do_something. If it is false(or nil) it will move on to the next line of code never running do_something.

这将首先评估if条件(在这种情况下a),如果是true(或在情况下a,不是falsenil),它将执行do_something。如果是false(或nil),它将移至下一行从未运行的代码do_something