@property or self.property to set a property using accessor?

This is a better practice; manipulating properties with accessories on @property or self.property ?

+6
ruby
source share
1 answer

If you just use direct accessors, stick with @property (unless you came from Python and disabled sigle @ ), otherwise:

It is completely up to you. But self.property can be useful in some cases when you need to make sure that the property is initially configured:

 def property @property ||= [] end # don't need to check if @property is `nil` first self.property << "hello" 

Also be careful that for self.property over @property there is little overhead, since self.property is a method call.

NOTE. The reason I use self.property only for property is because the corresponding setter method property= requires an explicit receiver: self.property= , so I choose to use an explicit receiver with both.

+1
source share

All Articles