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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With