Topic: wierd result

can anyone explain to me why this happends?

>> def foo
>>   returning [] do |x|
?>       x << ['x']
>>     end
>>   end
=> nil
>> foo
=> [["x"]]
>> def foo
>>   returning [] do |x|
?>       x |= ['x']
>>     end
>>   end
=> nil
>> foo
=> []

Last edited by boza (2010-08-18 16:43:26)

Re: wierd result

Pushing into the x array with << modifies the x array passed in by the returning method.

x |= [ 'x' ] creates a new array and stores it in local (to the block) variable x, overwriting the array passed by the returning method, however returning only knows about the original array and that is what it returns to you.

You can verify that they're different objects by looking at the object_id value of x in the block and the array returned by foo.

Rob Anderton
TheWebFellas