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 Basics!
You have completed Ruby Basics!
Preview
We've shown you how to call methods that Ruby defines for you. Now let's learn how to define your own methods.
- Defining a method
-
defkeyword - method name
- method body: one or more lines of code that will be run when method is called
- lines of method body are usually indented to make it clear they're a part of the method, although this isn't required
-
endkeyword
-
def wait
puts "Waiting..."
sleep 3
puts "Done"
end
def count_to_three
puts 1
puts 2
puts 3
end
- Valid method names
- All lower case
- Numbers are legal but rarely used
- Separate words with underscores. This is called snake case because it makes the name look like it's crawling on the ground.
- Call a method by typing its name in your code
count_to_three
wait
- Can call a method as many times as we want
count_to_three
count_to_three
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
3 seconds, and then print another
message that we're done waiting.
0:00
Lines 4, 5, and 6 count from 1 to 3.
0:04
These are two separate tasks in the same
program, but it's hard to tell at a glance
0:08
which lines belong to which task, or
what task they're supposed to be doing.
0:12
It's easy to define your
own methods in Ruby.
0:17
You start with the def keyword, short for
0:19
define, followed by the name
of the method you want.
0:22
So let's create a new
method here named wait.
0:25
And next we're going to need
a method body, that's one or
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