Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Attribute Readers1:46 with Jason Seifer
An attribute reader allows us to access variables in a class from outside that class. This is normally code we would have to write ourselves but Ruby gives us a shortcut in the form of an attribute reader.
class Name attr_reader :first_name, :middle_name, :last_name def initialize(title, first_name, middle_name, last_name) @title = title @first_name = first_name @midde_name = middle_name @last_name = last_name end end
Now that we know how to create and send in attributes when working on a class,
let's go ahead and fix up our name class with the different name attributes.
Now this pattern that we see right here,
where we are setting instance variables, and then calling them later.
It's something that's done quite a bit in Ruby.
And Ruby actually gives us a shortcut for doing this exact thing.
The shortcut is using a method called attr_reader which stands for
Now let's try it right here.
When we set the attribute reader as a title,
we can go down to the Title Method and take this out.
Now, if we run this program again, we should see the same thing printed.
And we do.
When we call the Adder Reader Method.
Ruby is actually writing this method for us.
It takes the name that we send in.
Which in this case is title.
And actually creates this method.
Which just returns the variable.
So we can go ahead and do that for all of our different named attributes.
Now our class just looks like this.
And let's go ahead and
run it and just make sure that everything is printed out the same way again.
And it works exactly as we expect it to.
You need to sign up for Treehouse in order to download course files.Sign up