Question

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?

Was it helpful?

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

OTHER TIPS

If a method identifier has ? as part of it, you would require an additional question mark.

> array_variable.include?('itemA') ? 'yes' : 'no'
>= "yes"

> array_variable.empty? ? 'yes' : 'no'
=> "no"

> array_variable.empty? 'yes' : 'no'
  SyntaxError: (irb):10: syntax error, unexpected ':', expecting end-of-input
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top