A weblog by Will Fitzgerald

Bad dog, Ruby, Bad dog!

>> x = [1, nil, 2]
=> [1, nil, 2]
>> x.find_all { |x| x}
=> [1, 2]
>> x
=> 2

2 responses to “Bad dog, Ruby, Bad dog!

  1. Michael Hannemann September 10, 2006 at 11:55 am

    Have you found out yet why “find_all” would be a destructive operation?

  2. Will September 10, 2006 at 5:27 pm

    It’s not “find_all,” but the scope of variables within blocks. From the 2nd edition of Programming Ruby (the “Pickaxe Book”):

    If the parameters to a block are existing local variables, those variables will be used as the block parameters, and their values may be changed by the block’s execution. The same thing applies to variables inside the block: if they appear for the first time in the block, they’re local to the block. If instead they first appeared outside the block, the variables will be shared between the block and the surrounding environment.

    with this footnote:

    3. Although extremely useful at times, this feature may lead to unexpected behavior and is hotly debated in the Ruby community. It is possible that Ruby 2.0 will change the way blocks inherit local variables.

%d bloggers like this: