From: Luther Date: 2006-11-15T16:13:43+09:00 Subject: Re: Design problem with 'inject' --- 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 You should use a '+' instead of a '+='. The return value of the block will be assigned to the next iteration's value for 'sum', so it doesn't make sense to modify 'sum' inside the block. > 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 Try it like this: arr.inject(0) do |sum, i| if i == 3 sum else sum + i end end Any time you want to skip an element, simply return 'sum'. This will carry the value from the last iteration on over to the next iteration, doing nothing with the current element. As far as I can see, you should never have to use 'next' in an inject block, unless you really want the intermediate result to be nil. Luther Thompson ____________________________________________________________________________________ Sponsored Link $420k for $1,399/mo. Think You Pay Too Much For Your Mortgage? Find Out! www.LowerMyBills.com/lre