Hi --

On Fri, 16 Feb 2007, joe / via.net wrote:

> If an operator is just syntactic sugar for a message send, how do I
> coose an operator based on an expression evaluation?
>
> For example:
>
> if a
>  s += "text"
> else
>  s = "text"
> end
>
> I should be able to write it something like this:
>
> s ((a)? send("+=") : send("=")) "text"
>
> Except the ruby compiler chokes on the syntax...

For several reasons :-)  = isn't a method, so you can't send it to an
object.  When you do:

   s = "whatever"

you are re-using the identifer 's', not operating on the object to
which it currently refers (if any).  Also, remember that 'send' itself
is a method.  At some point, you have to use regular method-calling
syntax (a dot, or falling back on the default receiver).

You could do the if/else version like this:

   s = if a
         s + "text"
       else
         "text"
       end

(which could all actually be on one line, give or take a 'then') or,
if you like the ternary thing:

   s = a ? s + "text" : "text"

or even:

   s = (a ? s : "") + "text"

And then, somewhat more bizarrely, there's:

   s = "#{a&&s}text"


David

-- 
Q. What is THE Ruby book for Rails developers?
A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black)
    (See what readers are saying!  http://www.rubypal.com/r4rrevs.pdf)
Q. Where can I get Ruby/Rails on-site training, consulting, coaching?
A. Ruby Power and Light, LLC (http://www.rubypal.com)