First, let’s try some of the basics. As you would expect, the local variables created in the blocks are not available outside them.
Also, as you would expect, variables created outside the block are available within them. (This bit of code calculates the first 10 Fibonacci numbers)
This feels pretty intuitive to me – the variables outside the block can be accessed and updated in the block.
In terms of variables declared outside the scope of the block – they don’t actually need to be accessed – the Ruby interpreter only needs to see them on the left side of an assignment.
To be fair, this isn’t really a weirdness with blocks – it’s simply a case of the Ruby interpreter creating the variable even though the assignment isn’t actually executed.
Block parameters are always scoped local to the block – again, this is pretty intuitive.
But, as we saw before – we can override variables outside the block.
Ruby 1.9 introduced the concept of block-local variables – simply list them in the block’s parameter list, preceded by a semicolon.