Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby multiline ternary expression?

I'm trying to convert something like this:

if condition?
   expression1 line 1
   expression1 line 2
   expression1 line 3
else 
   expression2 line 1
end

to a ternary, my question is: how do you put multiple lines into one expression on a single line? Do you separate by a semicolon like in java? Like this?

condition? expression1 line 1; expression1 line 2; expression1 line 3 : expression2
like image 721
matt lao Avatar asked Jan 15 '15 17:01

matt lao


People also ask

Does Ruby have ternary operator?

Ternary OperatorRuby has a nice option for short and concise conditional if statements. The ternary operator is a common Ruby idiom that makes a quick if/else statement easy and keeps it all on one line.

How does the ternary operator work in Ruby?

The conditional ternary operator assigns a value to a variable based on some condition. This operator is used in place of the if-else statement. The operator first evaluates for a true or false value and then, depending upon the result of the evaluation, executes one of the two given statements​.

What is the format of conditional operator?

The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.


2 Answers

In Ruby, it is always possible to replace newlines with semicolons, so you can, in fact, write your entire program in one single long giant line. Whether or not that is good for readability and maintainability, I will leave that up to you. (Note: you will sometimes have to insert parentheses for grouping in case of precedence mismatch.) Here is how you can write your conditional expression in a single line: if condition? then expression1 line 1; expression1 line 2; expression1 line 3 else expression2 line 1 end
like image 91
Jörg W Mittag Avatar answered Sep 19 '22 14:09

Jörg W Mittag


You can express ternary over multiple lines this:

condition ?
  expression 1 :
  expression 2

And yes you'll need to use semicolons for multiple expressions (and brackets won't hurt).

Please don't do this. Stick to if statements.

like image 26
Grocery Avatar answered Sep 17 '22 14:09

Grocery