...

/

Attribute Readers

Attribute Readers

This lesson explains the attribute readers and how they are related to instance variables.

Asking for information

Remember how we initially said 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. You also remember that methods are either questions or commands. We want to add a method that implements answering the question “What’s your name?”.

And it is as simple as this:

Press + to interact
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
person = Person.new("Ada")
puts person.name

So this prints the name Ada, and that’s what we want: we ...

Create a free account to access the full course.

By signing up, you agree to Educative's Terms of Service and Privacy Policy