Methods, Variables and Scope

Methods

Methods are a common structure. Define code abstraction, providing specific semantic and hiding implementation.

  • Parameterized Block code with a name: can be used with different parametric values per invocation.

def double(x)
    return x*2
end    

Variables and Scope

Variable: name for a mutable value

  • Ruby is a dynamically typed language, you can create a variable without specifying its type.

  • 4 types: local, global, instance, class.

  • Ruby allows the definitions of constant too.

# Local scope is the area where code that can use the binding 
#  between the name and the object ref value.
  • If the outside scope has some binding for variables with the same name used in the block scope, they are hidden inside the block and reactivated outside.

  • Note that statements like for, while, if, etc... do not define a new scope. Variables defined inside them are still accessible outside.

for i in 1..0
    a = i + 1
end

a === 11 # True
  • Methods does define its own scope and variables.

  • Generally, the following control structures define a new scope:

    • def ... end

    • class ... end

    • module ... end

    • loop {...}

    • proc {...}

    • iterators/method blocks

    • the entire script

  • You can also verify the scope of a variable using the defined? method.

Some tricks

# Multiple variable assignment
>> a,b,c = "a", "b", "c"

# Swap values
>> x = 10; y = 20
>> [x, y] = [y, x]

# Multi-variable assignment via a function
def ret_value
    return 1,2,3
end

one, two, three = ret_value

Last updated