The Wayback Machine - https://web.archive.org/web/20241126010026/https://www.geeksforgeeks.org/ruby-methods/
Open In App

Ruby | Methods

Last Updated : 06 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Method is a collection of statements that perform some specific task and return the result. Methods are time savers and help the user to reuse the code without retyping the code. Defining & Calling the method: In Ruby, the method defines with the help of def keyword followed by method_name and end with end keyword. A method must be defined before calling and the name of the method should be in lowercase. Methods are simply called by its name. You can simply write the name of method whenever you call a method. 

Syntax: 

def method_name
# Statement 1
# Statement 2
.
.
end

Example: 

Ruby




# Ruby program to illustrate the defining
# and calling of method
 
#!/usr/bin/ruby
 
# Here geeks is the method name
def geeks
 
# statements to be displayed
puts "Welcome to GFG portal"
 
# keyword to end method
end
 
# calling of the method
geeks


Output:

Welcome to GFG portal

Passing parameters to methods: In Ruby, parameter passing is similar to other programming language’s parameter passing i.e simply write the parameters in the brackets (). 

Syntax:

def method_name(var1, var2, var3)
# Statement 1
# Statement 2
.
.
end

Example: 

Ruby




# Ruby program to illustrate the parameter
# passing to methods
 
#!/usr/bin/ruby
 
# geeks is the method name
# var1 and var2 are the parameters
def geeks (var1 = "GFG", var2 = "G4G")
 
     #  statements to be executed
     puts "First parameter is #{var1}"
     puts "First parameter is #{var2}"
end
 
# calling method with parameters
geeks "GeeksforGeeks", "Sudo"
 
puts ""
 
puts "Without Parameters"
puts ""
 
# calling method without passing parameters
geeks


Output:

First parameter is GeeksforGeeks
First parameter is Sudo

Without Parameters

First parameter is GFG
First parameter is G4G

Variable Number of Parameters: Ruby allows the programmer to define a method that can take the variable number of arguments. It is useful when the user doesn’t know the number of parameters to be passed while defining the method. 

Syntax:

def method_name(*variable_name)
# Statement 1
# Statement 2
.
.
end

Example: 

Ruby




# Ruby program to illustrate the method
# that takes variables number of arguments
 
#!/usr/bin/ruby
 
# defining method geeks that can
# take any number of arguments
def geeks (*var)
     
   # to display the total number of parameters
   puts "Number of parameters is: #{var.length}"
    
   # using for loop
   for i in 0...var.length
      puts "Parameters are: #{var[i]}"
   end
end
 
# calling method by passing
# variable number of arguments
geeks "GFG", "G4G"
geeks "GeeksforGeeks"


Output:

Number of parameters is: 2
Parameters are: GFG
Parameters are: G4G
Number of parameters is: 1
Parameters are: GeeksforGeeks

Return statement in Methods: Return statement used to returns one or more values. By default, a method always returns the last statement that was evaluated in the body of the method. ‘return’ keyword is used to return the statements. 

Example: 

Ruby




# Ruby program to illustrate method return statement
 
#!/usr/bin/ruby
 
# geeks is the method name
def num
 
# variables of method
a = 10
b = 39
 
sum = a + b
 
# return the value of the sum
return sum
 
end
 
# calling of num method
puts "The result is: #{num}"


Output:

The result is: 49


Previous Article
Next Article

Similar Reads

Difference between Ruby and Ruby on Rails
Ruby is an object-oriented scripting language known for its simplicity and security, commonly used in developing desktop applications. Ruby on Rails is a web application framework built on Ruby, designed for creating database-driven web apps using the MVC architecture. It emphasizes principles like "Don’t Repeat Yourself" (DRY) and is known for its
4 min read
Ruby | Exception Class and its Methods
An exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at runtime, that disrupts the normal flow of the program’s instructions. In Ruby, descendants of an Exception class are used to interface between raise methods and rescue statements in the begin or end blocks. Exception objects carry information ab
3 min read
Ruby | Range Class Methods
Prerequisite: Ruby | Ranges Ruby provides a Range class. Ruby ranges depict a set of values with a beginning and an end. Values of a range can be numbers, characters, strings or objects. It is constructed using start_point..end_point, start_point…endpoint literals, or with ::new. It provides the flexibility to the code and reduce the size of code.
5 min read
Ruby | Thread Class-Public Class Methods
In Ruby, threads are used to implement concurrent programming module. Programs that required multiple threads, use the Thread class to create threads. Thread class contains a wide range of methods that perform some specified tasks. Public Class Methods abort_on_exception : This method returns the status of the global "abort on exception" condition.
4 min read
Ruby | Dir Class and its methods
A directory is a place for storing files. In Ruby, directories are handled by the Dir class and files are handled by the File class. In directories double dot(..) denotes parent directory and single dot(.) denotes directory itself. Class Methods 1. mkdir : This method is used to create a new directory. You can also put permission on the new directo
3 min read
Ruby Hook Methods
Ruby Hook Methods are called in reaction to something you do. They are usually used to extend the working of methods at run time. These methods are not defined by default, but a programmer can define them according to imply them on any object or class or module and they will come into picture when certain events occur. These methods help to extend
5 min read
Ruby - Singleton Methods
Ruby’s singleton methods are the methods that can be defined for a specific object only i.e. it works for a single object. These kinds of methods belong to the singleton class or eigenclass and are available exclusively for a single object, unlike the other methods which are available for all the instances of the class. This feature is more useful
2 min read
Private Classes in Ruby
The concept of private, protected and public methods in Ruby is a bit different than it other languages like Java. In Ruby, it is all about which class the person is calling, as classes are objects in ruby. Private Class When a constant is declared private in Ruby, it means this constant can never be called with an explicit receiver, a private cons
3 min read
Ruby | Matrix cofactor() function
The cofactor() is an inbuilt method in Ruby returns the cofactor of the given index. Syntax: mat1.cofactor(i, j) Parameters: The function needs two index i and j, whose cofactor is to be returned. Return Value: It returns the cofactor of the given index. Example 1: # Ruby program for cofactor() method in Matrix # Include matrix require "matrix
1 min read
Ruby Integer odd? function with example
The odd? function in Ruby returns a boolean value. It returns true if the number is odd, else it returns false. Syntax: number.odd? Parameter: The function takes the integer which is to be checked for odd or not. Return Value: The function returns a boolean value which determines if the value is odd or not. Example #1: # Ruby program of integer odd
1 min read
Ruby Integer div() function with example
The div() function in Ruby returns the integer division of two numbers. Syntax: (number1).div(number2) Parameter: The function needs two numbers number1 and number2, where number1 is the dividend and number2 is the divisor. Return Value: The function returns the integer division of two numbers. Example #1: # Ruby program of Integer div() function #
1 min read
Ruby | Symbol to_s function
Symbol#to_s() : to_s() is a Symbol class method which returns string representation of the symbol object. Syntax: Symbol.to_s() Parameter: Symbol values Return: string representation of the symbol object. Example #1 : # Ruby code for Symbol.to_s() method # declaring Symbol a = :aBcDeF # declaring Symbol b = :"\u{e4 f6 fc}" # declaring Sym
1 min read
Ruby | Set replace() function
The replace() is an inbuilt method in Ruby which replaces the contents of the set with the contents of the given enumerable object and returns self. Syntax: s1.replace(enum) Parameters: The function accepts an enumerable object which to be replaced in the set. Return Value: It returns the self object which contains the contents of the set after rep
1 min read
Ruby | Set reset() function
The reset() is an inbuilt method in Ruby resets the internal state after modification to existing elements and returns self. The elements will be reindexed and deduplicated. Syntax: s1.reset() Parameters: The function does not accepts any parameter. Return Value: It returns self . Example 1: # Ruby program to illustrate # the reset() method # requi
1 min read
Ruby | Array Concatenation using (+) function
Array#+() is a Array class method which performs set concatenate operation arrays by combining two arrays to a third array. Syntax: Array.+() Parameter: Arrays for performing the concatenation operation. Return: New arrays by combining two arrays. Example #1 : # Ruby code for +() method # showing concatenate operation # declaring array a = [18, 22,
2 min read
Ruby | at() function
The at() function in Ruby is used to return the element of the specified index. Index 0 is for the first element of the array, 1 for the second element of the array and so on. The negative index counts from the end of the input array. Syntax: Array.at(Index) Here Array is the input array of elements at which at() function is called. Parameters: Ind
2 min read
Ruby Float to_r() method with example
Float to_r() is a float class method which return a rational form of the float value. Syntax: float.to_r() Parameter: float value as argument Return: Rational form representation of the float value. Example #1 : # Ruby code for to_r() method # Initializing values a = 2.0 b = 9.99991 # Printing result puts "Rational form of a : #{a.to_r}\n\n
1 min read
Ruby | Keywords
Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects or as constants. Doing this may result in compile-time error. Example: # Ruby program to illustrate Keywords #!/usr/bin/ruby # here 'if' is a k
4 min read
Ruby | String inspect Method
inspect is a String class method in Ruby which is used to return a printable version of the given string, surrounded by quote marks, with special characters escaped. Syntax: str.inspect Parameters: Returns: Here, str is the given string. Example 1: # Ruby program to demonstrate # the inspect method # Taking a string and # using the method puts
1 min read
Ruby | String hex Method
hex is a String class method in Ruby which is used to treats the leading characters from the given string as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error. Syntax: str.hex Parameters: Here, str is the given string. Returns: A corresponding number. Example 1:
1 min read
Ruby | String include? Method
include? is a String class method in Ruby which is used to return true if the given string contains the given string or character. Syntax: str.include? Parameters: Here, str is the given string. Returns: true if the given string contains the given string or character otherwise false. Example 1: # Ruby program to demonstrate # the include? method #
1 min read
Ruby | Hash each_pair() function
Hash#each_pair() is a Hash class method which finds the nested value which calls block once for each pair in hash by passing the key_value pair as parameters. Syntax: Hash.each_pair() Parameter: Hash values Return: calls block once for key_value pair in hash with key_value pair as parameter otherwise Enumerator if no argument is passed. Example #1
2 min read
The yield Keyword in Ruby
We can send a block to our method and it can call that block multiple times. This can be done by sending a proc/lambda, but is easier and faster with yield. During a method invocation The yield keyword in corporation with a block allows to pass a set of additional instructions. When yield is called in side a method then method requires a block with
2 min read
Ruby | Struct to_s() function
The to_s() is an inbuilt method in Ruby that returns a string with the value of the particular struct. Syntax: struct_name.to_s() Parameters: The function does not accepts any parameter. Return Value: It returns the value of struct. Example 1: # Ruby program for to_s method in struct # Include struct animals = Struct.new(:name, :speciality , :found
1 min read
Ruby | Date === function
Date#===() is a Date class method which checks whether the two Date objects are equal. Syntax: Date.===() Parameter: Date values Return: true if two date objects are equal otherwise return false Example #1 : # Ruby code for Date.===() method # loading date require 'date' # declaring Date a = Date.new(2019, 1, 1) # declaring Date b = Date.jd(2452004
2 min read
Ruby | Date <=>() method
Date#<=> is a Date class method which compares two date objects. Syntax: Date<=>b Parameter: Date values Return: 1 if a is greater than b -1 if a is less than b 0 if a equals b Example #1 : # Ruby code for Date.<=>() method # loading date require 'date' # declaring Date a = Date.new(2019, 1, 1) # declaring Date b = Date.jd(2452004
2 min read
Ruby | Date - function
Date#-() is a Date class method which returns the difference between two dates if the object is date type object. Syntax: Date.-() Parameter: Date values Return: difference between two dates Example #1 : # Ruby code for Date.-() method # loading date require 'date' # declaring Date a = Date.new(2019, 1, 1) # declaring Date b = Date.jd(2452004) # de
2 min read
Ruby | Date + method
Date#+() is a Date class method which adds a numeric value to the date and returns a date object pointing other days after self. Syntax: Date.+() Parameter: Date values Return: date object pointing other days after self after adding a numeric value to the date. Example #1 : # Ruby code for Date.+() method # loading date require 'date' # declaring D
2 min read
Ruby | Complex + method
Complex#+() : +() is a Complex class method which performs the addition operation. Syntax: Complex.+()Parameter: Complex valuesReturn: Addition Operation on complex values. Example #1 : C/C++ Code # Ruby code for Complex.+() method # declaring Complex value a = Complex(200) # declaring Complex value b = Complex(-1, 4) # declaring Complex value c =
1 min read
Ruby | Array cycle() operation
Array#cycle() : cycle() is a Array class method which returns the array by calling the given block each time for every element in the array 'n' no. of times and if 'nil' is given, then it will call it for forever. Syntax: Array.cycle() Parameter: block - condition n - number of times to call the block Return: array by calling the given block each t
2 min read
Article Tags :
three90RightbarBannerImg