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, 0:00 let's go ahead and fix up our name class with the different name attributes. 0:05 Now this pattern that we see right here, 0:11 where we are setting instance variables, and then calling them later. 0:13 It's something that's done quite a bit in Ruby. 0:19 And Ruby actually gives us a shortcut for doing this exact thing. 0:22 The shortcut is using a method called attr_reader which stands for 0:28 attribute reader. 0:35 Now let's try it right here. 0:37 When we set the attribute reader as a title, 0:41 we can go down to the Title Method and take this out. 0:45 Now, if we run this program again, we should see the same thing printed. 0:50 And we do. 0:57 When we call the Adder Reader Method. 0:58 Ruby is actually writing this method for us. 1:01 It takes the name that we send in. 1:05 Which in this case is title. 1:07 And actually creates this method. 1:10 Which just returns the variable. 1:13 So we can go ahead and do that for all of our different named attributes. 1:18 Now our class just looks like this. 1:33 And let's go ahead and 1:37 run it and just make sure that everything is printed out the same way again. 1:38 And it works exactly as we expect it to. 1:43
You need to sign up for Treehouse in order to download course files.Sign up