0

Possible Duplicate:
What is attr_accessor in Ruby?

Here's the sample code:

class User
  attr_accessor :name, :email

  def initialize(attributes = {})
    @name = attributes[:name]
    @email = attributes[:email] 
  end 

....

end

When I do

example = User.new

it creates an empty user and I can assign its name and email by

example.name = "something"
example.email = "something" 

My question is, why this thing works? How does the computer know that example.name means the @name variable in the class? I'm assuming name and :name are different, and here in the code we have not explicitly told the computer that example.name is equivalent to :name symbol.

Community
  • 1
  • 1
OneZero
  • 11,556
  • 15
  • 55
  • 92

2 Answers2

5

What attr_accessor does is it creates a couple of methods, a getter and a setter. It uses a symbol you pass to construct names of methods and instance variable. Look, this code:

class User
  attr_accessor :name
end

is equivalent to this code

class User
  def name
    @name
  end

  def name=(val)
    @name = val
  end
end
Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
5

attr_accessor :field is the same as calling attr_reader :field and attr_writer :field. Those in turn are roughly the equal to:

def field
  @field
end

def field=(value)
  @field = value
end

Welcome to the magic of meta-programming. ;)

Koraktor
  • 41,357
  • 10
  • 69
  • 99