简体   繁体   中英

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? 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

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.

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 ? 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:

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

This works because if , like any other expression in Ruby, has a result. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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