- Demonstrate abstraction with methods
- Define "DRY"
- Recognize the structure of a method
- Recognize how to call methods
- Practice method calls
Methods are used to bundle one or more activities into a single unit. In daily life we do this all the time: "get ready for work" means: "take a shower, walk the dog, eat breakfast." But each of those activities is made up of other sub-activities, and sub-sub activities. "Take a shower" involves steps like "wash hair" which itself has steps like "wet head under the shower", "apply shampoo", etc.
Nearly all programming languages have the idea of "bundling up work" under a programmer-created name. While different languages might call them "subroutines," "methods," or "functions," they all mean the same thing: grouping work under a name that we think is appropriate.
In this lesson we'll introduce methods, distinguish them from data types, and cover how to create and execute them in your Ruby program.
This video provides an overview of everything we will learn and practice in next few lessons. We will revisit each of the discussed concepts in detail, but watching this video now will give you a good high-level view of how methods work.
<iframe width="560" height="315" src="https://www.youtube.com/embed/nTL_65lh76o" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>Methods define a new thing that your program can do. While variables in Ruby store data, methods store a new routine or behavior your program can use. Variables are like "nouns", things, and methods are like "verbs," actions.
For example, imagine needing to say "Hello World!" five times. It could look like this:
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
This meets the requirement all right. Now imagine that later in your program you want to say "Hello World!" five times again. We would have to write "Hello World!" five more times.
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
# Other work here...
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
But we're repeating the same String
over and over. Let's put that message as
variable called, helpfully, message
.
message = "Hello World!"
puts message
puts message
puts message
puts message
puts message
# Other work here...
puts message
puts message
puts message
puts message
puts message
Here we made use of a variable to store the message and didn't change anything else. You should be able to see here that by doing this our code is easier to change. From "Hello World!" we could easily go to "Hola Mundo!" by making one change versus making 10 changes.
But all those puts
appearing multiple times...there's something...that
bothers our programmer brains about this. It's seeing so much repetition.
Could we reduce the repetition somehow?
If we created a method to contain this "saying message
five times action" we
could get rid of some of that repetition.
Here's the method...
def say_hello_world_five_times
message = "Hello World!"
puts message
puts message
puts message
puts message
puts message
end
And, once integrated, our code could be much simpler:
def say_hello_world_five_times
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
puts "Hello World!"
end
say_hello_world_five_times
# other work
say_hello_world_five_times
Now, when we use the word say_hello_world_five_times
in our program, it
will invoke the method, running the code within the method.
This is cleaner. Programmers would say "We abstracted the 'action,' or
'procedure,' of puts
-ing 'Hello World!' five times into a method." Later, we'll
see ways of making this code even more abstract.
DRY stands for "Don't Repeat Yourself," a basic principle of software development aimed at reducing repetition of information. Less code is good: It saves time and effort, is easy to maintain, and also reduces the chances of bugs. When we see unsophisticated repetition, we want to reach for a form of abstraction. Creating methods is a common and powerful tool for abstraction.
Many research projects have looked at the relationship between lines of code and bugs. It turns out the only significant predictor of fewer bugs is...fewer lines of code!
Let's put a method's definition here so we can learn its parts:
def say_hello_world
puts "Hello World!"
end
When we define a method in Ruby, we use the def
keyword. A method's name
should begin with a lowercase letter.
The first line of def say_hello_world
is called the method signature.
The most important information in the signature is the method name. In the
example, the name of the method is say_hello_world
.
Later, we'll learn other things that we should put in the signature (helpful little variables called parameters), but for the time being we'll only define the method name in the signature.
The name of a
method should suggest what it does. If you need multiple words, Rubyists use a
_
to separate them. Separating words by an underscore (_
) is called
snake-case (because the shape looks like the words were swallowed up by a
snake).
Once you begin a method definition with the def
keyword, all following lines
until the method's closing end
keyword are called the method's body or
the method's implementation. The implementation is the actual code that your
method will run every time it's called. It's standard practice to indent the
body by two spaces when programming Ruby.
After multiple bits of work in the implementation or body, we
must provide an end
keyword.
TIP: A good practice is to define the method and then immediately close it with
end
before writing the body. Many expressions in Ruby usedo...end
and it can be confusing to keep them all balanced. By creating thedef (name)
...end
"bookends," and then filling in the implementation, we help prevent possible confusion.def greeting # type this first # # Third: start typing your implementation end # type this second
All this work defines a method. It does not run it โ yet. We must define it before we can use. Think of it like writing a recipe: writing the recipe does not mean doing the work of preparing the dish.
We've written the method, let's call it. Once you define a method, you can call or execute the method whenever you want by using the method name in your code.
def greeting
puts "Hello World"
end
greeting # Executing the method by name
#=> "Hello World"
greeting # Executing the method again
#=> "Hello World"
Some languages expect you to call methods by typing (greeting()
). Ruby doesn't
require this.
Let's code a method for ourselves, step by step. Create a new file called greeting.rb
. You can
use: touch greeting.rb
from your terminal to do so. Open up greeting.rb
in
your editor and paste the following code
into it:
def greeting
puts "Hello World"
end
If you save your file and try to run it with ruby greeting.rb
, you'll see:
$ ruby greeting.rb
$
You'll notice that when you run your program, there is no output and nothing
happens. We successfully defined the method, but never executed or called
it anywhere in the code. It's like we screwed in a new light bulb, but never
flipped the switch to "on." Ruby reads your definition of greeting
and then
says..."I'm done. Exit." Let's give it something to do before exiting: call
greeting
.
Update the code in greeting.rb
to read:
def greeting
puts "Hello World"
end
greeting
Now we've called the method at the bottom of our file. Save this file and run it
with ruby greeting.rb
. You'll see:
$ ruby greeting.rb
Hello World
$
Now your program actually executed the code in the method! Let's update the
code in greeting.rb
again to the following:
def greeting
puts "Hello World"
end
greeting
greeting
greeting
greeting
greeting
Now we've written greeting
five times at the bottom of the code. Save your
file and run it with ruby greeting.rb
. You'll see:
$ ruby greeting.rb
Hello World
Hello World
Hello World
Hello World
Hello World
$
The word greeting
will execute the body of the defined method for each
time it was called.
As a final step, we could write a method to do the work of "say greeting five times:"
def greeting
puts "Hello World"
end
def say_greeting_five_times
greeting
greeting
greeting
greeting
greeting
end
say_greeting_five_times
You should start to see that bigger programs could be build of methods calling sub-methods and those sub-methods calling sub-sub-methods โ just like we suggested in our example about "getting ready to go to work."
Methods are a big part of programming in Ruby and pretty much every language. We use them to save and perform repeatable actions. Knowing how to define and call methods is crucial to building programs, as well as your development as a programmer. You'll have to use them often, in big or small programs.
Ruby Programming/Syntax/Method Calls Ruby - Methods Ruby Methods