Ruby Ruby Objects and Classes Variables and Methods Variables and Methods

Kyle Shamblin
Kyle Shamblin
9,945 Points

Call the title method on the name instance. Syntax error?

I was finally able to fix this by typing name.title instead of Name.title. I thought you were supposed to use capitalization when calling a Class name. Is this just a "best practice" and not totally necessary?

class.rb
class Name
  def first_name
    "Metal"
  end
  def initialize(title)
    @title = title
  end
  def last_name
    "Robot"
  end
  def title
    @title
  end
end
name = Name.new("Kyle")
Name.title

1 Answer

Jay McGavren
STAFF
Jay McGavren
Treehouse Teacher

The reason calling Name.title doesn't work is because that attempts to call a method named title on the Name class itself, which doesn't exist. Instead, you want to create an instance of the Name class (a Name object), and call the title method on that instance (which does exist).

The point of confusion seems to be that we've asked you to use a variable name that's just a lower-case version of the class name. They might look the same to you, but since Ruby is case-sensitive, you might as well have used a totally different name for the variable, and it would have the same effect:

qyzzyg = Name.new("Kyle")
qyzzyg.title

That would work just as well in Ruby. (Although it might not pass the challenge, since it asks you to store it in a variable named name.)

Kyle Shamblin
Kyle Shamblin
9,945 Points

Ok, that totally makes sense now. Thanks for such a thorough explanation!