Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialClair Griffiths
10,158 PointsWhy do I have to create a title variable (wouldn't @title be sufficient?)
Hi there, I'm hoping someone can help explain something to me please.
In the attached code, as part of the initialize method, I think I'm creating a variable called @title which then contains the argument title when it has been passed in.
Why do I then have to create another variable called title which contains the variable @title? Could I not just call @title whenever I need it?
Many thanks in advance (these concepts are tough to get your head around!)
class Name
def initialize(title)
@title = title
end
def title
@title
end
def first_name
"Metal"
end
def last_name
"Robot"
end
end
name = Name.new("Clair")
1 Answer
Maciej Czuchnowski
36,441 Pointsdef title
creates a METHOD that returns the value of a variable, does not create a VARIABLE. Just like you have first_name and last_name methods. This allows you to query for specific attributes of the object, including the title. After creating a new object of this class usingthing = Name.new("Clair")
you can do this:
thing.title
thing.first_name
etc.
How else would you access the @title this way if you don't have the title method?
Clair Griffiths
10,158 PointsClair Griffiths
10,158 PointsPerfect explanation, thank you!