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:
|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
endkeyword 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)
valuewill store the value returned by the
The example here shows how we can create a function in Ruby:
myFuncfunction takes in a number, prints it, and returns the number’s double.
# Creating a Function def myFunc(num) puts "The number is: ", num return num * 2 end # Calling the function value = myFunc(4) # Printing return value puts "Returned valued is: ", value
View all Courses