How to do conditional operator?

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...

Joe

Hi --

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 :slight_smile: = 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

···

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

--
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)

harp:~ > cat a.rb
   a, s = 42, 'foo'
   s.send( a ? '<<' : 'replace', 'bar' )
   p s

   a, s = false, 'foo'
   s.send( a ? '<<' : 'replace', 'bar' )
   p s

   harp:~ > ruby a.rb
   "foobar"
   "bar"

-a

···

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...

Joe

--
we can deny everything, except that we have the possibility of being better.
simply reflect on that.
- the dalai lama