Controlling Variable Scope in Ruby 1.9

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

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

Tags: , , ,

3 Responses to “Controlling Variable Scope in Ruby 1.9”

  1. If you find yourself needing to do this, perhaps you should refactor and break up your methods a bit more.

    • i’ve never needed to use it myself, but i see a few ppl doing this kind of thing: proc { x = 5; something(x) }.call and i think a let/scope looks a bit prettier :)


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Get every new post delivered to your Inbox.

%d bloggers like this: