Introduce New Variable Without Polluting Global Namespace in Ruby
In my Ruby scripts, I often have some top level data structures, that are transformed by a series operations. These transformations are largely independent of each other, but complex enough so that they need local variables to get the work done.
1 | my_var = ... |
In C/Java, I can probably use curly braces, { // transform1 }
, to encapsulate all temporary local variables, but Ruby doesn’t support that…
Instead, Ruby has something like “self-invoking” function, which defines a new scope for local variables. Additionally, if I am super paranoid wrt
mutating the surround scope, I can use def function
so that the new scope doesn’t even have access to my top level variables. Technically, I don’t
need to wrap def function ... end
block in a “self-invoking” function, but the indentation provides a visual aid to discern its boundary. The
following snippet shows how the two solutions can be used.
1 | x = 1 |