On 10/7/07, Greg Willits <lists / gregwillits.ws> wrote:
> New to Ruby. Having trouble with ternary statements.
>
> I am used to a language that allows these two forms:
>
>    test ? trueStuff
>    test ? trueStuff | falseStuff
>
> While I have yet to find a reference that explicitly states this, it
> would appear that ternary statement in Ruby is not allowed to exclude
> the :, as without it I get an "unexpected '\n'" error statement.
>
> Ok, fine, so I can write something like this:
>
>    $debug ? $devLog.info("bla bla bla") :
>
> That's working for most cases, however, whenever such a line appears in
> IF statements, it generates another set of errors.
>
> if (...whatever...)
>   ...do some stuff...
>   $debug ? $devLog.info("bla bla bla") :
> else
>   ...do other stuff...
>   $debug ? $devLog.info("yadda yadda") :
> end
>
> I get "unexpected kELSE" and "unexpected kEND" syntax errors.
>
> Hard to comprehend what can be so tricky about a simple ternary
> statement. Indeed it is assumed to be so simple that the Programming
> Ruby book offers no details for its use, yet clearly there are some
> rules that need to be followed.

The ternary operator is not used very often, Ruby offers a different
way to do what you try.

do_stuff if test
do_stuff unless test

are both valid forms.

You cannot omit the third parameter from the ternary (that's why it
has this name, after all)
So if you want to make it work you have to:
test ? do_stuff : nil

Hope this helps, more information on the ruby quickref:
http://www.zenspider.com/Languages/Ruby/QuickRef.html