Reputation: 85
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?
Upvotes: 1
Views: 366
Reputation: 16507
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
Upvotes: 2
Reputation: 22926
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
Upvotes: 1