Tuesday, March 16, 2010

block parameter scope weirdness

If the fact that external variables can be changed inside a block isn't strange enough for you, check out this example. What would you presume happens to "index" during the method call?

index = "watch this space"
my_array = ["base", "basket", "tennis", "goof"]
my_array.map {|index| index += "ball"}

It is a little alarming, but index is now equal to "goofball." This could make for some very unexpected and undesired behavior if you are not careful about what you are naming your block parameters. Dangerous!

No comments:

Post a Comment