1

I've created a Person class and my code is correct, but I just wanted someone to clarify a specific line.

class Person 
  attr_reader :first_name, :last_name, :age

  def initialize (first_name, last_name, age)  
    @first_name = first_name  
    @last_name = last_name
    @age = age
  end
end

The line I'm confused about is the attr_reader one. Why does this need to be included and why do I need the : before each attribute?

Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214
ppreyer
  • 6,547
  • 4
  • 20
  • 18

2 Answers2

5

attr_reader is a convenience method that ruby provides for adding the following method in an automated manner(getter methods). I.e. just one line of code will add these three methods in your case.

As for taking a symbol as input arguments, well that is how the method was defined. You can look a bit more at http://ruby-doc.org/core-1.8.7/Module.html#method-i-attr_reader

def first_name
  @first_name
end

def age
  @age
end

def last_name
  @last_name
end
sohaibbbhatti
  • 2,672
  • 22
  • 21
1

Ruby does not allow public access to instance variable, attr_reader is actually a method added to the class Class which gives a easy way to access instance varible.

class Class
    def attr_reader(*args)
        *args.each do |arg|
            self.class_eval("def #{arg}; @#{arg}; end")
         end
    end
end

class_eval above just insert the code in ur class definition and evaluate them ;)

Thiem Nguyen
  • 6,345
  • 7
  • 30
  • 50
Yang Chen
  • 11
  • 1