Coder Social home page Coder Social logo

programming-univbasics-3-defining-methods-lax-web-100719's Introduction

Methods in Ruby

Learning Goals

  • Demonstrate abstraction with methods
  • Define "DRY"
  • Recognize the structure of a method
  • Recognize how to call methods
  • Practice method calls

Introduction

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.

breaking down steps of activities and sub-activities

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.

Video: Methods

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

Demonstrate Abstraction With Methods

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.

We sense something wrong about this

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.

Define DRY

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!

Recognize the Structure of a Method

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 use do...end and it can be confusing to keep them all balanced. By creating the def (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.

Recognize How to Call Methods

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.

Practice Method Calls

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."

Conclusion

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.

Resources

Ruby Programming/Syntax/Method Calls Ruby - Methods Ruby Methods

programming-univbasics-3-defining-methods-lax-web-100719's People

Contributors

maxwellbenton avatar drakeltheryuujin avatar

Watchers

 avatar  avatar Victoria Thevenot avatar Bernard Mordan avatar Otha avatar raza jafri avatar  avatar Joe Cardarelli avatar The Learn Team avatar Sophie DeBenedetto avatar  avatar  avatar Matt avatar Antoin avatar  avatar Alex Griffith avatar  avatar Amanda D'Avria avatar  avatar Ahmed avatar Nicole Kroese  avatar Kaeland Chatman avatar Lisa Jiang avatar Vicki Aubin avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.