Functions and Blocks

Functions in Ruby

A function is a block of code that can be called from another location in the program or class.


Syntax
#standard functions
#if within a class, called on the object
def functionName(passedParameters)

   #code to be executed

   #optional return value or variable
   return value
   #another way to return value
   value
end

Notes

It is used to reduce the repetition of multiple lines of code.

A function can either return nil, a value, or an array of values. If multiple items are returned, they will be returned as an array.


Example
def absolute_value(x)
    if x < 0
        x = x * -1
    end
    return x
end

Add to Slack

< Throw and Catch   |   Blocks >

© 2018 SyntaxDB. All Rights Reserved.