...

/

Attribute Readers

Attribute Readers

This lesson explains attribute readers and how they’re related to instance variables.

Asking an object for information

Remember that people have the ability to remember their name, and tell it, when asked.

We’ve already implemented the first part of this. Our Person instance now knows her name, “Ada”.

Let’s look at the second part. Remember also that methods are either questions or commands. We want to add a method that answers the question, What’s your name?

It’s as simple as this:

Press + to interact
Ruby
class Person
def initialize(name)
@name = name
end
def name
@name
end
end

Before we discuss what this does, let’s look at how we can use our new method. We can now call the method on the person object, like this:

Press + to interact
Ruby
person = Person.new("Ada")
puts person.name

This prints the name, Ada, and that’s ...