Setting an attribute from a model without using self does not work

The device model has the following attributes: name, version, and full_name

Full name is name + version:

class Device < ActiveRecord::Base def prepare full_name = (!show_version || version.nil?)? name : name + " " + version.to_s end end 

When I do the following:

 d = Device.new :name => "iPhone", :version => "4" d.prepare d.full_name # get nil 

I get nil for the attribute "full_name"

When I use "self", it works:

 class Device < ActiveRecord::Base def prepare self.full_name = (!show_version || version.nil?)? name : name + " " + version.to_s end end 

Performing "prepare", I get "iPhone 4" for the attribute "full_name".

Some people have told me that this is a good way to avoid using the "I" inside class methods. But it brings problems.

Question: why doesn’t it work without using "I"?
+4
source share
2 answers

In these cases you should use yourself, I do not think this is a problem. If you use self , then the interpreter will know that you are referring to an attribute of the object. If you do not use self , it means that it is just a local variable that is not stored anywhere after the method completes. This is normal behavior. You can also use self[:full_name]= ... as the setter method, but in this case it doesn't really matter.

Update

@AntonAL

Because getter methods are recognized without self. .

When you try to use the name attribute, the interpreter will look for a local variable in the current method. If it does not find, then it searches for the attribute of the instance. Example:

 def your_method self.name = 'iPhone' puts name #iPhone name = 'iPod' puts name #iPod puts self.name #iPhone end 

And the iPhone will be saved in your instance of the name object instance. And the iPod will be lost after the method is completed.

+13
source

When you use setters, you need to use self , because otherwise Ruby interprets it as a new local variable full_name .

For getters, we do not need to call self , because Ruby first looks for the local variable full_name , and when it does not have the local variable full_name , it will look for the full_name method and get a getter. If you have a local variable defined by full_name , it will return the value of the local variable.

This is better explained in the previous question.

+11
source

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


All Articles