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 –
On Fri, 16 Feb 2007, [email protected] wrote:
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
On Fri, 16 Feb 2007, [email protected] wrote:
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