Table of contents
1.
Introduction
2.
Methods in Ruby
3.
Defining Simple Methods in Ruby
4.
Passing Multiple Parameters 
5.
Method Termination
6.
Class Methods
7.
Invoking a Method on an Object
8.
Frequently Asked Questions
8.1.
What do you mean by Ruby?
8.2.
What is a method in Ruby?
8.3.
What is the process of defining simple methods in ruby?
8.4.
What is the difference between methods and procs in Ruby?
8.5.
How to call a method in Ruby?
9.
Conclusion
Last Updated: Mar 27, 2024

Defining Simple Methods in ruby

Author Ayushi Goyal
0 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Ruby is a high-level language, interpreted, and object-oriented programming language that is general-purpose, dynamic, and reflective. Except for blocks, which have replacements in the form of procs and lambda, everything in Ruby is an object. The goal of Ruby's development was to create a user interface between human programmers and the computational machinery that underpins them.

introduction

Ruby's syntax is similar to many other programming languages, including C and Java, making learning easy for Java and C programmers. It runs on various OS(Operating Systems), including Windows, Mac OS X, and Linux.

Let's talk about the methods in ruby and how to define them in Ruby.

Methods in Ruby

what are methods

Methods in Ruby are similar to the functions in other programming languages. These methods group one or more repeated statements into a single unit. According to the naming convention, a method name should start with a lowercase letter. Otherwise, the Ruby compiler will consider it a constant, resulting in an incorrect call. Moreover, unlike C++, methods in ruby must be defined before they are called. Otherwise, the compiler will raise an exception. 

Let's see the process of defining simple methods in ruby.

Defining Simple Methods in Ruby

defining simple methods

Defining Simple Methods in ruby includes the definition, which is done using the 'def' keyword, followed by the method name and a list of parameters, if available, to end the method body 'end' keyword.

Syntax-

def method_name(parameter1, parameter2)
   # Method body 
   # Statement-1
   # Statement-2 
   # And so on…
end
You can also try this code with Online Ruby Compiler
Run Code


The value of these parameters comes from the arguments passed during method invocation.

For Example-

def sum(a, b)
  print“Sum is = ”
  return a+b
end

print(sum(6,4))
You can also try this code with Online Ruby Compiler
Run Code


Output

passing parameter output

This code defines a method name ‘sum’ that will return the sum of two given numbers. The method consists of 2 parameters: 'a' and 'b'. The invocation of this method is done inside the print statement with the values of parameters to print their sum.

Passing Multiple Parameters 

Ruby allows us to pass multiple parameters inside method definition. It is beneficial when the number of parameters are not known while defining the method.

def name(*arr) 
    for i in 0...arr.length
        puts "Names are: #{arr[i]}"
    end
end

# Passing two parameters
name "Coding", "Ninja"

# Passing single parameter
name "XYZ"
You can also try this code with Online Ruby Compiler
Run Code

 

Output

multiple parameter output\

Method Termination

A method in Ruby can be terminated normally or abnormally. An abnormal termination condition occurs when an exception is thrown by the method. The 'sum' method shown above is completed normally because the last statement of this method body will execute without any exception. 

method flow

The 'return' statement is used to end the execution of the method and transfer the control flow back to the main code block at the point from where the method is invoked. However, we try to omit the return statement when not required. 


In Ruby, we can return more than one value using an explicit return statement and separating the values by commas. These multiple values are stored in an array. For example:

def show(a, b)
  return a,b
end

x,y = show(5,6)
print "Value of x - "
print x
print "\nValue of y - "
print y
You can also try this code with Online Ruby Compiler
Run Code


Output

multiple return output

Class Methods

The methods declared inside the class are known as class methods. If the method definition is given outside the class then it is considered private by default, while the methods defined inside the class are considered public. To access the class methods we have to create objects of the class, using which we can access these methods. 

Ruby also allows you to directly access the methods without creating objects of these classes using dot(.) operator. Syntax - Class_name.method_name

Let's see an example for clear understanding:

class Coding_Ninjas
    def name 
        print "Print Names of Students"
    end 
end

# Accessing using class 
Coding_Ninjas.name 
You can also try this code with Online Ruby Compiler
Run Code


Output

class method output

Invoking a Method on an Object

Invoking method

An object is sometimes called a receiver; the methods are called messages and sent to receiver objects. While defining simple methods in Ruby, the 'self' keyword refers to an object on which the method is invoked. If the object is not specified, then the method is implicitly called by this self keyword. 

Hope you are now capable of defining simple methods in ruby.
Check out this problem - Subarray Sum Divisible By K

Frequently Asked Questions

What do you mean by Ruby?

Ruby is a high-level, interpreted, high-level, general-purpose programming language that supports multiple programming paradigms.

What is a method in Ruby?

A method in Ruby is a collection of one or more statements used to perform a sort of specific task and return the result.

What is the process of defining simple methods in ruby?

In Ruby, a method is defined with the help of the 'def' keyword followed by method_name and ends with the 'end' keyword. A method must be defined before calling, and the method's name should be in lowercase.

What is the difference between methods and procs in Ruby?

Methods are invoked within an object, and methods are created by the Object#method and are associated with a particular object. While a proc object is an encapsulation of a block of code, which can be stored in a local variable, passed to a method or another Proc.

How to call a method in Ruby?

Methods are called by their name. You can write the name of the method whenever you call a method. 

Conclusion

This blog covered the details on defining simple methods in ruby. We learned what methods are, how to define and invoke them, and the return value of methods, along with examples.

If you want to learn more, check out our articles/blogs on ruby and refer to Ruby Documentation for more information. You can also learn more about ruby from the links given below.

Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, JavaScript, System Design, etc. Enroll in our courses like Competitive Programming and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.

Thank you

Do upvote our blog to help other ninjas grow. 

Happy Learning Ninja! 🐱‍👤

Live masterclass