Search code examples
rubysyntaxternary

ruby ternary operator syntax - spacing between operator


Is the following line proper ruby syntax?

session[:id]?'foo':'bar'

(Notice there is no spacing between the operators)

This line works with all the rubies I tried (>1.8.7) but I understand there can be a misunderstanding as the ? can be part of a method identifier.

Shouldn't it be a syntax error to not put spaces arround the ternary operator?


Solution

  • I believe the correct forms the ternary operator are when selector is the indexed hash, because the char combination ]? is invalid for the same operator:

    session[:id]?'foo':'bar'
    session[:id] ? 'foo' : 'bar'
    session[:id]? 'foo' : 'bar'
    

    But if you omit the space after just the a method and the question mark, this will raise the syntax error:

    session?'foo':'bar'
              ^
    SyntaxError: unexpected ':', expecting $end
    session? 'foo':'bar'
               ^
    SyntaxError: unexpected ':', expecting $end