Software dev, tech, mind hacks and the occasional personal bit

Ruby 1.8 Scoping and Blocks

Quick ruby quiz.. after these two lines execute, what is the value of number?

>> number = 5
>> (1..10).each {|number| print number}

Well, number will be 10, thanks to the block being run and re-assigning the value of number. This can cause you some pretty subtle bugs if you happen to have the same name for a local/function argument, and as a variable name in a block.

In C#, the compiler is kind enough to tell you that this would be a very bad idea and give you an error.

And thanks to Sudhinda for commenting – this has been fixed in Ruby 1.9. In 1.9, the variable used as the argument in the block does not affect the variable outside the block.

Previous

Showing Hidden Files in Mac Finder

Next

Odd Date and Time Comparisons in Rails & Hack night

3 Comments

  1. Hi James,

    This is true only in Ruby 1.8(known bug) and before. As of 1.9 the behaviour is as you would expect. Variables in blocks do not override variables outside them. More predictable behaviour now.

    -Sudhindra

  2. Thanks Sudhinda for the info, I was using Ruby 1.8.7. I’ve updated the post.

  3. Normal behaviour, cause with ruby 1.8 blocks variable have local scope.
    “In Ruby 1.8.x, block variables were introduced into the scope that the block was called from ..”

    @Sudhindra Is it really a bug? , i don’t think so, no ?

    – Philippe Cantin

Powered by WordPress & Theme by Anders Norén