From: Robert Klemme Date: 2006-11-15T17:45:05+09:00 Subject: Re: Design problem with 'inject' On 15.11.2006 07:50, 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 In this case I would not even resort to #next. This seems much more straightforward: arr.inject(0) {|sum, i| i == 3 ? sum : sum + i} or, if you do not like the ternary operator arr.inject(0) {|sum, i| if i == 3 then sum else sum + i end} IMHO #next is best used if the block is /long/ and you want to short circuit to the next iteration. If it is a short block like in this case #next does not bring any benefits and in fact makes it more complicated to understand - at least in my opinion. Kind regards robert