defining self-reflexive operators in Ruby

H

Harry Spier

In the same way that a += 1 means a = a+1
is it possible in Ruby to create an operator such as .! (or something
like that) such that
someObject.!someMethod gives the same result as
someObject = someObject.someMethod
 
R

Roger Pack

In the same way that a += 1 means a = a+1
is it possible in Ruby to create an operator such as .! (or something
like that) such that
someObject.!someMethod gives the same result as
someObject = someObject.someMethod

I've often wondered the same thing, but could never figure out an
elegant syntax for it.
 
R

Ryan Davis

=20
In the same way that a +=3D 1 means a =3D a+1
is it possible in Ruby to create an operator such as .! (or something
like that) such that
someObject.!someMethod gives the same result as
someObject =3D someObject.someMethod

no.

someObject isn't the object, it is just a local variable reference to =
it. Objects don't know what variables or other objects refer to them. =
Ruby's syntax is opaque, so it wouldn't be possible to write something =
(in ruby, which is what you asked for) that could operate at parse-time =
in this way (without fully pre-parsing, munging, and re-eval'ing. At =
that stage, I wouldn't call it "in ruby").
 
R

Robert Klemme

In the same way that a += 1 means a = a+1
is it possible in Ruby to create an operator such as .! (or something
like that) such that
someObject.!someMethod gives the same result as
someObject = someObject.someMethod

Even if it was (but see the other replies) it would not be a good idea.
The reason is this:

class BangAndNoBang
def foo
x = dup
x.foo!
x
end

def foo!
# work
end
end

In other words: for efficiency reasons you would always implement method
x in terms of x! instead the other way round.

Kind regards

robert
 

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,145
Messages
2,570,826
Members
47,372
Latest member
LucretiaFo

Latest Threads

Top