Method is a collection of statements that perform some specific task and return the result. Methods allow the user to reuse the code without retyping the code. 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.
def method_name # Statement 1 # Statement 2 . . end
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 ().
def method_name(var1, var2, var3) # Statement 1 # Statement 2 . . end
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.
def method_name(*variable_name) # Statement 1 # Statement 2 . . end
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.
The result is: 49
- Ruby | Dir Class and its methods
- Ruby Hook Methods
- Ruby - Singleton Methods
- Ruby | Range Class Methods
- Ruby | Exception Class and its Methods
- Ruby | Thread Class-Public Class Methods
- Ruby | BigDecimal % value
- Ruby | BigDecimal >= value
- Ruby | BigDecimal * value
- Ruby | BigDecimal + value
- Ruby | BigDecimal <= value
- Ruby | BigDecimal ** value
- Ruby | BigDecimal > value
- Ruby | BigDecimal +@ value
- Ruby | Hash == value
- Ruby Literals
- Ruby Tutorial
- Ruby | Set > method
- Ruby | pop() function
- Ruby | Set <= method
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.