Search code examples
rubyternary-operator

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

Solution

  • You should wrap the expressions in parenthesis:

    condition ? (expression1 line 1; expression1 line 2; expression1 line 3) : expression2
    

    You should keep in mind that this reduces readability of your code. You are probably better off using an if/else statement to improve readability. One resource I like to use when reviewing my ruby code is the community style guide. As it says in the introductory paragraph:

    This Ruby style guide recommends best practices so that real-world Ruby programmers can write code that can be maintained by other real-world Ruby programmers.

    Hope this helps