2

I have a question about what the best way is to reference a class variable in Ruby.

Here is a class I made:

class Person
  attr_accessor :name

  def initialize(name)
    @name = name
  end

  def say_name
    puts @name
  end

  def say_name2
    puts self.name
  end

end

bob = Person.new("Bob")

bob.say_name 
=> "Bob"

bob.say_name2
=> "Bob"

Both of the "say_name" methods seems to work as intended. Why use the @variable vs the self.variable??

Brock Tillotson
  • 119
  • 1
  • 8

1 Answers1

3

attr_accessor :name just creates method name, which returns @name variable, something like

def name
  @name
end

instead of you.

Without attr_accessor both self.name and name will not work and return NoMethodError. @name will work in all cases.

max pleaner
  • 26,189
  • 9
  • 66
  • 118
Ilya
  • 13,337
  • 5
  • 37
  • 53