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.


Actions

Information

3 responses to “Ruby 1.8 Scoping and Blocks”

23 10 2010
Sudhindra Rao (13:56:11) :

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

23 10 2010
James (15:34:15) :

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

25 10 2010
Philippe (21:08:09) :

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