Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Ruby Ruby Objects and Classes Variables and Methods Variables and Methods

Clair Griffiths
Clair Griffiths
10,158 Points

Why 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.rb
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
Maciej Czuchnowski
36,437 Points

def 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
Clair Griffiths
10,158 Points

Perfect explanation, thank you!