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
Methods are extremely useful and powerful when writing classes. A method can manipulate the data inside of an instance of a class and return or format that data in new and interesting ways.
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
end
name = Name.new("Mr.", "Jason", "", "Seifer")
puts name.full_name_with_title
nick = Name.new("Mr.", "Nick", "", "Pettit")
puts nick.full_name_with_title
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
We can write methods inside of our
classes.
0:00
Writing methods inside of classes is
powerful, because the methods can
0:01
apply only to the individual instance that
we're working with.
0:05
Let's go ahead and take our Name class and
add a method to it now using Workspaces.
0:10
So, we've got our Name class and I just
changed this to be an attr_accessor for
0:16
a title, first name, middle and last name.
0:21
So, we know that we're going to have all
of those different methods set for us.
0:23
Now, we can create our own methods to work
with in classes.
0:28
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