0

I don't understand why 'attributes=' inside of initialize should have prefix self.

'name' method doesn't need to have prefix self to call 'attributes' method

class A
 attr_accessor :attributes

  def initialize attrs ={}
    self.attributes = attrs
  end

  def name 
    puts attributes
  end
end

a = {"name" => "someone"}
b = A.new a

b.name

output {"name" => "someone"}

if self.attributes = attrs change to attributes = attrs output gonna be nil

helloyi621
  • 41
  • 5
  • This all depends on how Ruby sees `attributes=` in the body of your `initialize` method. Without `self` to force it to be a method call it's often interpreted as a variable assignment. – tadman May 24 '16 at 15:38
  • Not "often". *Always* `foo = bar` is *always* assigning to a local variable named `foo`. In fact, that's how Ruby distinguishes between local variable references and method calls: `foo` is a local variable reference if and only if an assignment `foo = bar` has been parsed before. – Jörg W Mittag May 24 '16 at 15:42

1 Answers1

1

If you use attributes = attrs you will just assign attrs to the local variable attributes just as you could assign attrs to some_other_var. By prepending attributes with self. you specify that the accessor needs to be used.

  • I thought attributes= defined by attr_accessor, how to explain def name puts attributes end. – helloyi621 May 24 '16 at 15:36
  • Calling the get `attributes` accessor does a lookup, first if there is locally a variable named `attributes`, if there is not it looks for an instance method named `attributes`, in this case it will find it as you have defined it with `attr_accessor`. For assignment with `attributes=` there is no way to distinguish between local variable assignment and the instance setter method which is why you need to disambiguate it with the `self.attributes=` – Maarten van Vliet May 25 '16 at 10:02