0

A lot of times I see inside a class instance variables get changed with the @ sign. For example, @name = "kitty" but since there is a attr_accessor :name. We could also write just name = "kitty" in the class.

Is there a significant different between using @name vs name (with attr_accessor)? I understand that they take different pathways. @name is direct while using self.name calls on the class method but in the end result it is the same thing?

Bri Expost
  • 101
  • 8
  • 3
    “We could also write just `name = "kitty"`”—we cannot. Setters must be called with an explicit receiver, otherwise the local variable `name` will be created instead of setting a value to an instance variable. Save for that, both assignments are absolutely equal. – Aleksei Matiushkin Jun 03 '18 at 07:51
  • @mudasobwa Oh wait, youre right. One question though. Lets say name was an instance variable with an attr_reader. Is there a difference between doing name.length vs @name.length? They both have the same result. – Bri Expost Jun 03 '18 at 08:09
  • No, they don't. `name` is a message send which resolves to a method call. Methods can be overridden in subclasses, they can be monkey patched, they can be proxied, they can be intercepted. `@name` is a variable reference. You can do none of those things with a variable reference. – Jörg W Mittag Jun 03 '18 at 08:50

0 Answers0