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 trial

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,441 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!