Ruby Methods Tutorial

In this section, we will learn what methods are and how to use them in Ruby.

What is a Method in Ruby?

The Ruby method is a block where we can put a set of codes (instructions) and label the method with a name. At a later time then we can call that block with its name anywhere in the program in order to execute the instructions within the body of that method.

The reason we use methods is mainly because we might have a set of instructions in a program that is needed in multiple places. So instead of just writing those instructions in every places (basically copying it everywhere) we can simply write it in one place and then simply call it anywhere in the program that is needed.

Your program is smart enough to find the actual source code of the method you’ve called and invoke its instructions.

Ruby Method Syntax and Definition: Defining a Method in Ruby

def method_name (parameter1, parameter2, parameter_n)

#instructions of the method...

end

Ruby def Keyword

The keyword `def` stands for the word define and we use it when we want to create a method. This is part of the syntax of a method and Ruby uses this keyword to realize that a method is created.

Method Identifier in Ruby

`method_name`: this is basically the label and the name of the method where we use in later time to invoke the method in order to execute its instructions. Note that the rules we apply to variables when setting their names apply to the name of methods as well.

A method identifier is basically the name of that method. So when we say a method identifier, we’re actually pointing to the name of a method.

Method Parameters in Ruby

`(parameter1, parameter2 …)`: Sometimes a method in order to function correctly needs input as well. For example, your method might be a set of instructions that runs multiplication operation. So this method to work appropriately, it needs an input value right? Now the question is, if we call the method and somehow pass it its required inputs, where these inputs will be stored then?

This is where we use parameters.

Parameters are local variables that are used in the head of a method after its name and they will store the inputs that the target method will take when its being called.

Now depending on how many inputs a method might need, we can define 0 or more parameters for a method. If a method is taking more than one parameter, we need to separate those parameters using comma `,`.

Note that the use of a pair of parentheses around the parameters is optional and we can remove it.

For example:

def method_name parameter1, parameter2, parameter_n

#instructions of the method...

end

Here’s the convention: if a method has one or more parameters, the convention is to use a pair of parentheses around those parameters. But if the target method does not take any parameter, then we should not use parentheses at all.

For example:

def method_name

#instructions of the method…

end

Ruby Method end Clause:

`end`: this clause defines the closing border of the target method. Now, within the body of the method we can put any necessary instructions (codes) that we want to be run when that method is getting called.

Example: Ruby method with multiple parameters

def print_name (first_name, last_name)

    puts first_name, last_name

end

In this example, the name of the method is `print_name` and it has two parameters named `first_name` and `last_name`. So when we wanted to call the method we need to use the name `print_name` and because this method has two parameters, we need to pass two input values (AKA argument) to the method at the time of calling it.

Example: setting parameters for methods in Ruby

def print_details (first_name, last_name, age, email)

    puts first_name, last_name, age, email

end

In this example, the method’s name is `print_details` and it has 4 parameters with the names `first_name`, `last_name`, `age`, and `email`. Note that they are separated using a comma `,`.

So now if we wanted to call this method we need to use the name `print_details` and also assign 4 input values to this method so that each parameter get a value assigned to it.

Calling a Method in Ruby: How to Call a Method in Ruby?

Here’s the syntax of how to call a method:

method_name (input1, input2, input_n)

`method_name`: this is the name of the method we want to call.

`(input1,input2, input_n)`: if the target method has one or more parameters, we then need to pass a value for each of those parameters. For example, if the method has 3 parameters, then we need to pass three arguments (input value) to the method at the time of calling the method. Note that each input value is separated using a comma.

But if the target method does not have any parameter, then we only need to call the name of that method without any parentheses or input value.

Note: if a method has parameters, we should pass exactly the same number of input value (AKA argument) as the number of parameters of that method. Adding more or less argument to the method would cause error!

Example: calling a method in Ruby

def print_details (first_name, last_name, age, email)

    puts first_name, last_name, age, email

end

print_details("John","Doe", 80, "[email protected]")

Output:

John

Doe

80

[email protected]

In this example, the name of the method is `print_details` and it has 4 parameters. This means we need to pass 4 input values (arguments) to the method when we’re calling it.

In this example, we called the method with 4 arguments and behind the scene this is what happened:

The first argument is passed to the `first_name` parameter as:

first_name = “John”

The second argument is passed to the `last_name` parameter as:

last_name = “Doe”

The third argument is passed to the `age` parameter as:

age = 80

And the fourth parameter is passed to the `email` parameter as:

email = “[email protected]

So now, considering the fact that parameters are nothing but local variables of a method, we can easily use these variables in our method wherever they are needed.

What is Argument in Ruby?

The input value that we pass to a method is called argument!

Ruby return Statement

A method is capable of returning a value when it is being called.

In order to return a value from a method, we use the keyword `return`.

Any value that we put on the right side of the `return` keyword will be returned from the method the moment our program reach to this statement.

Note that when the `return` statement is called, your program will terminate that method or basically exit from the method with that value as its final value. This means you can’t put any instructions after the `return` statement and expect it to be executed!

Example: using return statement in Ruby

def print_details (first_name, last_name, age, email)
    puts first_name, last_name, age, email

    return "Hello #{first_name}"
end 


result = print_details("John","Doe", 80, "[email protected]")

puts result

Output:

John

Doe

80

[email protected]

Hello John

If we look into the body of the `print_details` method, we can see that its last statement is a call to the `return` statement where it returns the value “Hello” + the value of the `first_name` parameter.

So for this reason, when we called the method and passed the value `John` as the argument of the `first_name` variable, the method returned the string value “Hello John” and we assigned that value to the `result` variable.

Note: other than using the `return` statement, we can implicitly return a value from a method as well. This is explained in the Ruby return keyword Tutorial.

Ruby Local Variables

A variable that we create within the body of a method is called local variable.

They are called local variables because other than the body of the target method, there’s no way of accessing the variable from outside of the method.

Basically, to other methods, a local variable is as if it doesn’t exist!

Also the life time of a local variable is limited to the time when the target method is running! This means, the moment a method is closed and finished its work, the local variable of that method will be destroyed.

Example: creating local variables in Ruby

def function_one
    first_name = "Jack"
end 

def function_two
    puts first_name
end 

function_one
function_two

Output:

undefined local variable or method `first_name' for main:Object

In this example, we have two methods with no parameters.

In the `function_one` method we have one local variable called `first_name`. Note that this is a local variable and that means we can’t access the method from outside of the `function_one`.

But we tried to call the `first_name` variable within the body of the other method `function_two`.

That’s why we got an error in the output stream.

Difference between Parameter and Argument in Ruby

A parameter is a local variable that we set for a method in its header when we’re creating the method. But an argument is the input value we pass to a method when the method is being called.

More to Read:

Ruby return Statement

Ruby Optional Default Arguments

Ruby Keyword Argument

Ruby local and global variables

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies