I have a class that has a method:
def value=(valueIN)
some code
end
and this does exactly what I want when I do:
(class instance).value="new data"
It seems like it would be cleaner if I could just override the =
for this class so I do not have to do value=
. First, I tried:
def =(valueIN)
some code
end
but this gave me an error, so then I tried:
def self=(valueIN)
some code
end
This does not cause an error, but it does not work when I do:
(class instance)="new data"
Is the assignment something that is not changeable at the class level? If this cannot be done, its not really a big deal, but I was hoping I am missing something basic.
Sorry, you can't do this. When you write foo = bar
, you're just assigning a variable, not calling any method. It's only something.foo = bar
that desugars to a method call, and just like everywhere else, the receiver of that method call is the thing before the dot.
=
is not an operator in Ruby that could be overwritten. The trick Ruby plays (with us) is, that
self.value = "Me"
self.value= "You"
self.value=("He")
are all interpreted the same, so that you are free to use the version you like most. Because these are all method calls, you can define or overwrite how value=
with one argument should work.
It is an idiom to use that only for assigning attributes of objects, but Ruby allows you to use it where you want.
So no chance to overwrite the =
operator (which I think is a good idea).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With