Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Preview
Start a free Courses trial
to watch this video
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
A common idiom that Ruby programmers use
when writing classes and
0:00
instances is to use the to_s method.
0:04
This method is a convention, and
0:08
is called by Ruby when an object wants to
be formatted as a string.
0:10
Let's see how that works now with the name
class using workspaces.
0:16
Okay, so here's our name class and
0:21
it's just like before except I took out
the attribute reader for
0:24
first and middle name and put it back to
what we have before with full name.
0:29
Now let's take a look at what happens when
we print out just the name so
0:33
I'm gonna write ruby name.rb.
0:38
And we see that we get this funny little
format right here,
0:43
which is the name of the class and its
address in memory.
0:48
Whenever we print something out to the
screen using the puts method,
0:53
internally Ruby is calling to string on it
or to_s.
0:59
And we can override that in our classes if
we want to.
1:04
[BLANK_AUDIO]
1:07
So if we look here, we've got this to_s
method.
1:15
And let's just have this print out the
full name with the title.
1:19
[BLANK_AUDIO]
1:23
Now when to_s is called is should print
out the full name.
1:28
And there we go.
1:34
It can be very useful when you're working
with your own classes to
1:36
define a to_s method.
1:40
Another method that we could use if we
wanna find out
1:44
a little bit more about the object we're
working with is the inspect method.
1:46
Inspect will tell you the internal state
of the object that youβre working with.
1:53
So here we can see the same thing as
before, itβs the name class.
1:59
And the place in memory or the object ID.
2:04
And we also have a listing of all of the
internal instance variables
2:07
of the class as well as their values.
2:13
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