How to do conditional operator?

J

joe

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
 
D

dblack

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 :) = 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)
 
A

ara.t.howard

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

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,234
Messages
2,571,178
Members
47,809
Latest member
Adisty

Latest Threads

Top