简体   繁体   English

在Ruby代码中使用空格(三元运算符)

[英]Using whitespace in Ruby code (the ternary operator)

Considering this piece of code: 考虑到这段代码:

values = ["one", "two", "", "four"]

values.each do |value|
puts value.empty? ? "emptyness" : "#{value} is #{value.length}"
end

is it possible in Ruby 1.8.7 to format the ternary operator indenting the operands? 是否有可能在Ruby 1.8.7中格式化三元运算符缩进操作数? Something like: 就像是:

puts value.empty?
    ? "emptyness" 
    : "#{value} is #{value.length}"

but this one obviously won't work. 但这显然不会奏效。

The way to do this using Ruby itself with no escapes is to have Ruby know that it is waiting for more information 使用Ruby本身没有转义的方法是让Ruby知道它正在等待更多信息

puts value.empty?  ?
  "emptyness" :
  "#{value} is #{value.length}"

The reason for this is Ruby sees the parts of the ternary and knows that something more is needed to complete the statement. 这样做的原因是Ruby看到了三元组的部分,并且知道完成语句需要更多的东西。

Using parenthesis in the OP's code would not work, the statements would still be partial, and Ruby would not know what to do with the ? 在OP的代码中使用括号不起作用,语句仍然是部分的,Ruby不知道如何处理? and : on the next line. 并且:在下一行。

Of course, you don't really need the ternary: 当然,你真的不需要三元:

values = ["one", "two", "", "four"]

values.each do |value|
  puts value.empty? && "emptyness" ||
    "#{value} is #{value.length}"
end

You can use the character \\ to split the command into newlines. 您可以使用字符\\将命令拆分为换行符。

This will work: 这将有效:

values = ["one", "two", "", "four"]

values.each do |value|
   puts value.empty? \
     ? "emptyness" \
     : "#{value} is #{value.length}"
end

Also, you can't have any space after the \\ character or a syntax error will be raised. 此外,在\\字符或语法错误引发后,您不能有任何空格。

When the ternary operator needs to be split into multiple lines, it may be time to use an if instead: 当三元运算符需要分成多行时,可能需要使用if代替:

puts if value.empty?
       "emptyness"
     else
       "#{value} is #{value.length}"
     end

This works because if , like any other expression in Ruby, has a result. 这是有效的,因为如果像Ruby中的任何其他表达式一样有结果。 That result is the result of either the then or the else section, whichever got executed (and if the condition is false and there is no else section, then the result of the if is nil). 该结果是thenelse部分的结果,无论哪个执行(如果条件为false且没有else部分,则if的结果为nil)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM