Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

override the "=" operator in ruby

Tags:

ruby

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.

like image 276
fullobs Avatar asked Dec 20 '22 08:12

fullobs


2 Answers

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.

like image 121
Chuck Avatar answered Dec 29 '22 03:12

Chuck


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

like image 39
mliebelt Avatar answered Dec 29 '22 04:12

mliebelt