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.
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.
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.
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
Last updated