Ruby classes: initialize self vs. @variable
ruby
Solution
In general, no, `self.stuff = stuff` and `@stuff = stuff` are different. The former makes a method call to `stuff=` 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 :stuff` on classes. `attr_accessor` is roughly equivalent to the following:
def stuff
@stuff
end
def stuff=(s)
@stuff = s
end
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:
def stuff
@stuff_called += 1 # Keeps track of how often this is called, a side effect
return @stuff
end
def stuff=(s)
if s.nil? # Validation, or other side effect. This is not triggered when setting the instance variable directly
raise "Argument should not be nil"
end
@stuff = s
end
Problem
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?