I find that I get errors if I use “puts” in it’s standard form in a
ternary operator
x == 2 ? puts “two” : puts “one”
error is:
SyntaxError: (irb):3: syntax error, unexpected tSTRING_BEG, expecting
keyword_do or ‘{’ or ‘(’
x == 2 ? puts “two” : puts “one”
^
(irb):3: syntax error, unexpected ‘:’, expecting $end
x == 2 ? puts “two” : puts “one”
^
It works however if I use this form:
x == 2 ? puts(“two”) : puts(“one”)
Could someone help me figure out why? Is there documentation somewhere
on this?
thanks
On Fri, Jul 22, 2011 at 4:18 PM, Jesse B. [email protected]
wrote:
SyntaxError: (irb):3: syntax error, unexpected tSTRING_BEG, expecting
keyword_do or ‘{’ or ‘(’
x == 2 ? puts “two” : puts “one”
^
(irb):3: syntax error, unexpected ‘:’, expecting $end
x == 2 ? puts “two” : puts “one”
I think the lack of parens creates an ambiguous scope for the
argument to the initial puts
whereas your next form doesn’t.
x == 2 ? puts(“two”) : puts(“one”)
Regardless you could DRY it up (without even parens) as
puts x == 2 ? “two” : “one”
FWIW,
On Sat, Jul 23, 2011 at 7:18 AM, Jesse B. [email protected]
wrote:
(irb):3: syntax error, unexpected ‘:’, expecting $end
x == 2 ? puts “two” : puts “one”
^
imho,
ruby is trying to read it as:
x == 2 ? puts (“two” : puts “one”)
it reads the puts first, but then it encounters the colon, so…
It works however if I use this form:
x == 2 ? puts(“two”) : puts(“one”)
or:
x == 2 ? (puts “two” ) : (puts “one” )
Could someone help me figure out why? Is there documentation somewhere
on this?
use parens to help the interpreter
kind regards -botp
A syntax for a tenary operator is:
(exp)? :
and is always the one object - I think that ruby
can’t tell whether you’re trying to call puts or push two or more
elements in these “fields”. So use the parenthesized form to call a
function.
PS. Sorry for my not technical language ;).
Yours,
Martin
2011/7/23 Jesse B. [email protected]:
On Jul 22, 2011, at 16:18 , Jesse B. wrote:
It works however if I use this form:
x == 2 ? puts(“two”) : puts(“one”)
puts x == 2 ? “two” : “one”