Sometimes it can be handy to have precise control over the scope of a variable. In C and C++ we can do this by defining a new scope (a curly brace pair) and in lisp by using the let and let* special operators. Ruby (AFAIK) has no native way of doing this. However we can hack together something that behaves similarly to C’s ‘scopes’ and lisps ‘let’ by making use of the new block variable scoping rules in Ruby 1.9.

We use it like this:

x = 1 y = 2 let { |x, y| x = 10 y = 20 } x #=> 1 y #=> 2

Note that in the above the block variables ‘x’ and ‘y’ shadow the ‘x’ and ‘y’ variables defined in the outer scope. This is consistent with the behaviour of C’s scopes and lisp’s let.

We can also use the fact that block parameters in Ruby 1.9 now accept default values, and so we can get behaviour very similar to lisp’s let* special operator:

let { |x = 20, z = (x * 3)| x #=> 20 z #=> 60 }

And here is the code:

def let yield end

I’m not sure how much practical use any of this has but I think it’s quite a cute little trick 🙂

Share this: Twitter

Facebook

Reddit

Like this: Like Loading... Related