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