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