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.
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. |
A function in Ruby is created as follows:
def myFunc(param)
body
return <value>
end
The
end
keyword is used to mark the end of a function in Ruby.
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
value
will store the value returned by themyFunc
function.
The example here shows how we can create a function in Ruby:
The
myFunc
function 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