How to create a function in Ruby
A function is a snippet of code that can be repeatedly used whenever it is called. We use functions to divide the functionality of a program into smaller parts that we can handle separately.
Basic syntax
Any generic function can be broken down into three parts:
| Parts | Description |
|---|---|
| Definition | This is the first line that defines a function, gives it a name, and passes parameters (if available). |
| Body | The code within the function. |
| Return statement | This returns a calculated value or some solution. |
Syntax
A function in Ruby is created as follows:
def myFunc(param)
body
return <value>
end
The
endkeyword is used to mark the end of a function in Ruby.
Calling a function
A function is called using its name and passing in parameter values (if the function requires).
We can call the function myFunc, as follows:
value = myFunc(myParam)
The variable
valuewill store the value returned by themyFuncfunction.
Example
The example here shows how we can create a function in Ruby:
The
myFuncfunction takes in a number, prints it, and returns the number’s double.
# Creating a Functiondef myFunc(num)puts "The number is: ", numreturn num * 2end# Calling the functionvalue = myFunc(4)# Printing return valueputs "Returned valued is: ", value
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved