Override operator "=" in 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 this:

 (class instance).value="new data" 

It seems like it would be cleaner if I could just override = for this class, so I don't need to do value= . First, I tried:

 def =(valueIN) some code end 

but this gave me an error, so 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 an assignment something that doesn't change at the class level? If this cannot be done, it is not very important, but I was hoping that I was missing something.

+4
source share
5 answers

Sorry, you cannot do this. When you write foo = bar , you simply assign a variable without calling any method. It is just something.foo = bar that desugars to call the method, and just like everywhere else, the receiver of the call to this method is the thing in front of the dot.

+4
source

= not a Ruby operator that can be overwritten. Ruby trick plays (with us) that

 self.value = "Me" self.value= "You" self.value=("He") 

all are interpreted the same way, so you can use the version that you like best. Since these are all method calls, you can define or overwrite how value= should have one argument.

The idiom uses this only to assign attributes to objects, but Ruby allows you to use it wherever you want.

Thus, there is no way to rewrite the = operator (which I think is a good idea).

+2
source

= interpreted in one of two ways, depending on the context.

  • part of the form method foo= Assignment Operator

You can define your own method in the form foo= , in which case = preceded by an alphabet, but you cannot override the variable assignment operator = .

+1
source

It is impossible to do what you are talking about. You cannot change the value of self , so for = there is no redefinition of the class level.

I'm not quite sure why you want to do this. Scenarios in which this may be useful will require the creation of a new instance of the class. You can perform similar actions by cloning an object (via .dup or something else) and changing a new one, or creating your own class method to copy the object and return a new, possibly modified instance. I ponder but cannot come up with a good example.

+1
source

If you are trying to provide a setter method for a class level value, you can do this using something like this:

 class MyClass def self.my_class_attribute=(value) @my_class_attribute = value end end 

Then you can assign it like this:

 MyClass.my_class_attribute = "new value" 

This calls the .my_class_attribute= method on MyClass .

0
source

Source: https://habr.com/ru/post/1468894/


All Articles