Method

We can divide a program into procedural components or modules called methods in Ruby. We are already familiar with functions like print(), get(), step() and length(). Methods can be copied and reused in a programming technique called the modular or procedural approach, also known as the divide and conquer approach. We should always try to design methods that can be reused in other programs too.

Broadly, there are two types of methods, which we’ll explore in the following sections.

Structure of a method

The following slides illustrate various parts of a method definition:

A method name can only contain letters (AZ and az) and the underscore symbol (_). It may also contain digits (09), but the function name can’t start with those. For example, Key_2 is a valid function name, but 2_key is not. Function names are case-sensitive, meaning that name, Name, and NAME are three different methods.

There are three main parts of a method definition:

  • Header: This is the first line containing def.
  • Body: This is the block of statements below the method header.
  • Ending-point: This is the last line containing end.

The method header contains the keyword def, the method name sayHello, and the parentheses().

Let’s write code for the above example.

Press + to interact
def sayHello() # Definition of function
print("Hello")
end
sayHello()

In the last line, we’re telling the program to run the function sayHello(). This line is known as a method call or calling the method.

Execution sheet for method calls

Let’s look at the following code before working on its execution sheet:

Press + to interact
def first()
print("Now inside the Method \"first\".\n")
end
def second()
print("Now inside the Method \"second\".\n")
end
print("Main program is starting here.\n")
first() # calling first
print("Back in main program.\n")
second()# calling second
print("Back in main program again.\n")

In the program:

  • We define two simple methods—first and second.
  • We demonstrate the sequence of execution with the help of print statements.

The most important column to understand the sequence of execution is the PS# column. The sequence of PS# for the above program is 7,8,1,2,9,10,4,5,117, 8, 1, 2, 9, 10, 4, 5, 11.

Here’s another code snippet to help us understand the execution sequence of method calls. The sequence of PS# for the following program is 9,10,4,5,6,1,2,7,119, 10, 4, 5, 6, 1, 2, 7, 11.

Press + to interact
def deeper()
print('Now inside the method "deeper".',"\n")
end
def deep()
print('Now inside the method "deep".',"\n")
deeper(); # Call method deeper
print('Now back in "deep".',"\n")
end
print('Main program is starting here.',"\n")
deep() # Call method deep
print('Back in the main program.',"\n")

The execution sequence can also be visualized like so:

The above illustration shows the PS# and the depth of each method call more clearly. The first two statements are from the main program, the next three from the method deep(), the next one from the method deeper(), and the last one again from the main program. The main program is the caller of the deep() method. The deep() function is the caller of deeper().

The return statement

The following slides illustrate another method that returns a value. The example shows (1) how to use the return statement in the method body and (2) how to write the parameters (a,b) in the method header.

Note: Every method in Ruby is a value-returning method. When we don’t have a return statement, Ruby implicitly returns None.

Let’s write the code for the above example.

Press + to interact
def getSum(a,b) # Definition of the function
mysum = a + b # Adding a and b and assigning the result in variable mysum
return mysum # returning mysum value
end
print(getSum(5,6))

In the above code:

  • The last line calls the print() method. It invokes the getSum method with the values 5 and 6 as arguments for the parameters a and b respectively.
  • The variable mysum holds the sum of a and b, which is 11.
  • The statement return mysum returns 11 to the print() statement as a result of the method call.

Note: The figure in this section is here to highlight that the return statement has to be the last statement in the method body. Any statement written in the method body after the return statement is unreachable.

Practice creating and calling methods

The following are a few example programs to practice creating and calling methods. By clicking the “Show Solution” button, you’ll find a program that solves the respective problem. You can copy and paste the given solution into the code widget to make sure that the output of your solution matches the given solution. There may be several ways of writing correct solutions in programming.

Function to create a multiplication table

Write a function showTableOf4() that displays 20 terms of the table of a value received as a parameter. Call the showTableOf4() function with distinct argument values one by one.

Sample output

4 x 1 = 4
4 x 2 = 8
4 x 3 = 12
4 x 4 = 16
4 x 5 = 20
4 x 6 = 24
4 x 7 = 28
4 x 8 = 32
4 x 9 = 36
4 x 10 = 40
4 x 11 = 44
4 x 12 = 48
4 x 13 = 52
4 x 14 = 56
4 x 15 = 60
4 x 16 = 64
4 x 17 = 68
4 x 18 = 72
4 x 19 = 76
4 x 20 = 80
Press + to interact
# Write your code below

Method to find distinct values

Write a method showDistinct that takes an array as a parameter and prints the distinct elements in the array. It’s assumed that the array is already sorted in ascending order. Call your function to display the results.

Sample input 1

[2, 5, 5, 8, 8, 8, 9, 30, 45]

Sample output 1

Original array: [2, 5, 5, 8, 8, 8, 9, 30, 45]
Distinct array: [2, 5, 8, 9, 30, 45]

Sample input 2

[2, 5, 5, 8, 8, 8]

Sample output 2

Original array: [2, 5, 5, 8, 8, 8]
Distinct array: [2, 5, 8]
Press + to interact
# Write your code below

Method to search a string in an array

Write a method that checks if a string or character is present in the array. If it’s present, display its index in the array. Call your function to display the results.

Sample input 1

  • First parameter: array
    ['2','55','888','9','30','45']
    
  • Second parameter: string
    '888'
    

Sample output 1

 888 is found at index 2

Sample Input 2

  • First parameter: array
    ['2','55','888','9','30','45']
    
  • Second parameter: string
    '50'
    

Sample output 2

50 is not found in the array
Press + to interact
# Write your code below

Method to display the Fibonacci sequence

A Fibonacci sequence is a sequence in which each number is the sum of the two preceding ones. Write a method, fibo, that receives the parameter n to specify the number of terms of the Fibonacci sequence. The value of n should be less than or equal to 20. That method will return an array containing the sequence. Call your function to display the results.

Sample input

10

Sample output

First 10 terms of Fibonacci sequence are:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
*** End of generating Fibonacci Numbers ***
Press + to interact
# Write your code below