Functions
Published Jul 27, 2021Updated Sep 9, 2021
Contribute to Docs
Functions are a set of instructions that return one value. Functions that exist in an object are typically called methods.
Function Basics
A function is declared using the def
keyword. We close a function with the end
keyword.
def greetingputs "Hello, World!"returnend# Output: Hello, World!# Output => nil
Functions with Parameters
Functions can take parameters. Parameters are variables that are passed into a function.
def greeting(name)puts "Hello, #{name}!"returnendgreeting("John")# Output: Hello, John!# Output => nil# Parentheses are optional when calling a functiongreeting "Mary"# Output: Hello, Mary!# Output => nil
Explicit and Implicit Return
If the return
keyword is not used, the last expression in the function will be returned.
def greeting(name)return "Hello, #{name}!"endgreeting("John")# Output: => Hello, John!# Returns the value of the last expression evaluateddef greeting(name)"Hello, #{name}!"endgreeting("Mary")# Output: => Hello, Mary!
Default Values
Default values may be provided and will be used if no argument is passed to our function.
def greeting(name="human")return "Hello, #{name}!"endgreeting# Output: => Hello, human!
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.