From: Farrel Lifson Date: 2006-11-15T15:59:52+09:00 Subject: Re: Design problem with 'inject' On 15/11/06, Marcel Molina Jr. wrote: > On Wed, Nov 15, 2006 at 03:46:44PM +0900, Gary Boone wrote: > > Ruby's inject has a design that can lead to hard to find bugs. The > > problem is that you don't have to specify what is summed; the value of > > the block is summed. That means 'next' can lead to a bug. Here's an > > example: > > > > No problem: > > > > arr.inject(0) do |sum, i| > > sum += i > > done > > > > But suppose you need to skip some elements, so you add a 'next' > > statement. > > Problem: > > > > arr.inject(0) do |sum, i| > > next if (i==3) > > sum += i > > done > > You need to do this: > > next sum if i == 3 > > Also: > > sum += 1 > > This unecessarily modifies the sum. > > sum + 1 > > Will suffice. > > marcel > -- > Marcel Molina Jr. Whoa! That is good to know. Farrel