Ruby 多行三元表达式?

Ruby multiline ternary expression?

我正在尝试转换这样的东西:

if condition?
   expression1 line 1
   expression1 line 2
   expression1 line 3
else 
   expression2 line 1
end

对于三元,我的问题是:如何将多行放在一行的一个表达式中?您是否像 java 中那样用分号分隔? 像这样?

condition? expression1 line 1; expression1 line 2; expression1 line 3 : expression2

您应该将表达式括在括号中:

condition ? (expression1 line 1; expression1 line 2; expression1 line 3) : expression2

请记住,这会降低代码的可读性。您最好使用 if/else 语句来提高可读性。我在审查 ruby 代码时喜欢使用的一种资源是 community style guide。正如介绍性段落中所说:

This Ruby style guide recommends best practices so that real-world Ruby programmers can write code that can be maintained by other real-world Ruby programmers.

希望这对您有所帮助

您可以在多行中表达三元:

condition ?
  expression 1 :
  expression 2

是的,您需要对多个表达式使用分号(括号不会造成伤害)。

Please don't do this, per rubocop style. 坚持单行,或 if 块。

三元运算符需要一个指令块。这意味着您要么使用括号

对指令进行分组
condition = true
condition ? (puts("this"); puts("is"); puts("true")) : puts("this is false")

或在 begin/end 块中。

condition = true
condition ? begin puts("this"); puts("is"); puts("true") end : puts("this is false")

事实上,没有简单、干净的方法来实现结果,应该告诉您三元运算符并不是真正为多语句设计的。 ;)

这种情况下不要尝试使用它。使用标准 if/else.

In Ruby, it is always possible to replace newlines with semicolons, so you can, in fact, write your entire program in one single long giant line. Whether or not that is good for readability and maintainability, I will leave that up to you. (Note: you will sometimes have to insert parentheses for grouping in case of precedence mismatch.) Here is how you can write your conditional expression in a single line: if condition? then expression1 line 1; expression1 line 2; expression1 line 3 else expression2 line 1 end