From: Brian Candler Date: 2010-08-04T17:12:51+09:00 Subject: Re: Remove the error Amir Ebrahimifard wrote: > Hi > Why these codes result error ? > > 1- > array = [*1..10] > sum = array.inject { |memo,item| memo+item if item !=3 } sum = array.inject(0) { |memo,item| item != 3 ? memo+item : memo } Note a subtlety here: if you omit the (0) argument then the initial memo is always set to the first item, so you wouldn't be able to skip it. >> array.inject { |memo,item| item != 1 ? memo+item : memo } => 55 >> array.inject(0) { |memo,item| item != 1 ? memo+item : memo } => 54 > 2- > array = [*1..10] > sum = array.inject { |memo,item| puts memo+item } sum = array.inject { |memo,item| puts memo,item; memo+item } In both cases, you need to ensure that the last expression evaluated by the block is the value you want for the 'memo' in the next iteration. -- Posted via http://www.ruby-forum.com/.