Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
- Variables 4:48
- Variables and Methods 4 objectives
- Attribute Readers 1:46
- Attribute Readers 1 objective
- Attribute Writers and Accessors 5:20
- Attribute Writers and Accessors 2 objectives
- Methods 3:31
- Methods 1 objective
- Instance Variables and Local Variables 4:54
- Instance Variables and Local Variables 4 questions
- The to_s method 2:16
- The to_s Method 1 objective

- 2x 2x
- 1.75x 1.75x
- 1.5x 1.5x
- 1.25x 1.25x
- 1.1x 1.1x
- 1x 1x
- 0.75x 0.75x
- 0.5x 0.5x
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 up-
David Greenstein
6,734 Points1 Answer
-
MICHAEL P
5,191 PointsNoticed a Mistake That Jason Made In Teacher's Notes Vs Video
Posted by MICHAEL PMICHAEL P
5,191 Points0 Answers
-
lindseyk
4,506 PointsI'm not totally clear on the reason one should create a to_s method?
Posted by lindseyklindseyk
4,506 Points1 Answer
-
Jory Braun
7,814 Points1 Answer
View all discussions for this video
Related Discussions
Have questions about this video? Start a discussion with the community and Treehouse staff.
Sign up
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