"HTML" was retired on January 6, 2020. You are now viewing the recommended replacement.
Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Well done!
You have completed Ruby Objects and Classes!
You have completed Ruby Objects and Classes!
Preview
A common idiom that Ruby programmers use when writing classes is to define a `to_s` method, which tells Ruby how to print out a class.
Code Samples
class Name
attr_accessor :title, :first_name, :middle_name, :last_name
def initialize(title, first_name, middle_name, last_name)
@title = title
@first_name = first_name
@middle_name = middle_name
@last_name = last_name
end
def full_name
@first_name + " " + @middle_name + " " + @last_name
end
def full_name_with_title
@title + " " + full_name()
end
def to_s
full_name_with_title
end
end
name = Name.new("Mr.", "Jason", "", "Seifer")
puts name.full_name_with_title
puts name
puts name.inspect
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign upRelated Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
This method is a convention, and
0:00
is called by Ruby when an object wants to
be formatted as a string.
0:01
Let's see how that works now with the name
class using workspaces.
0:07
Okay, so here's our name class and
0:12
it's just like before except I took out
the attribute reader for
0:15
first and middle name and put it back to
what we have before with full name.
0:20
Now let's take a look at what happens when
we print out just the name so
0:24
I'm gonna write ruby name.rb.
0:29
You need to sign up for Treehouse in order to download course files.
Sign upYou need to sign up for Treehouse in order to set up Workspace
Sign up