Dek Dekku
Dek Dekku

Reputation: 1461

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.

Upvotes: 3

Views: 2092

Answers (3)

vgoff
vgoff

Reputation: 11313

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

Upvotes: 6

Wayne Conrad
Wayne Conrad

Reputation: 107989

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).

Upvotes: 2

Pigueiras
Pigueiras

Reputation: 19356

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.

Upvotes: 5

Related Questions