Share

Strange behaviour of Enumerable#each_with_object and array concatenation

Update: Brian VanLoo posted a very helpful comment explaining the behaviour I saw.  Scroll down to the comments and read it to understand what's going on here.

I've been bitten several times by an apparent bug in ruby, using Enumerable's each_with_object method. The problem appears to occur when passing an array as the target object, and adding to this object with +=. The values added to the array don't appear to remain in the array, and the returned array is empty.

It's probably best described by some code, and I wrote a gist that shows it pretty well. Using Array#concat works, whereas += does not. The other option is using a normal each loop and adding to the array, which also works.

Is this a bug? Or have I missed something? I'm in the progress of submitting a bug report to ruby (but I'm having trouble with my account's confirmation email not being delivered), but if anyone can tell me why this isn't a bug then I'll be very grateful.

← Previous post: Creating a Cinch plugin part 2: a word game bot for IRC Next post: Creating a Cinch plugin part 3: a word game bot for IRC →
comments powered by Disqus