Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 232
Dek Dekku Avatar asked Apr 22 '26 14:04

Dek Dekku


1 Answers

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
like image 150
vgoff Avatar answered Apr 24 '26 06:04

vgoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!