Can someone explain the difference between initializing “self” and having @variables when defining classes?
Here’s an example
class Child < Parent
def initialize(self, stuff):
self.stuff = stuff
super()
end
end
So in this case, wouldn’t I be able to replace self.stuff with @stuff? What’s the difference? Also, the super() just means whatever is in the Parent initialize method the Child should just inherit it right?
In general, no,
self.stuff = stuffand@stuff = stuffare different. The former makes a method call tostuff=on the object, whereas the latter directly sets an instance variable. The former invokes a method which may be public (unless specifically declared private in the class), whereas the latter is always setting a private instance variable.Usually, they look the same because it is common to define
attr_accessor :stuffon classes.attr_accessoris roughly equivalent to the following:So in that case, they are functionally identical. However, it is possible to define the public interface to allow for different results and side-effects, which would make those two “assignments” clearly different: