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
def geeks
puts "Welcome to GFG portal"
end
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
def geeks (var1 = " GFG ", var2 = " G4G ")
puts "First parameter is
puts "First parameter is
end
geeks "GeeksforGeeks", "Sudo"
puts ""
puts "Without Parameters"
puts ""
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
def geeks (*var)
puts "Number of parameters is:
for i in 0 ...var.length
puts "Parameters are:
end
end
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
def num
a = 10
b = 39
sum = a + b
return sum
end
puts "The result is:
|
Output:
The result is: 49
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
06 May, 2022
Like Article
Save Article