From: Colin Bartlett Date: 2009-10-25T19:26:29+09:00 Subject: Re: convert/replace a value of nil with 0? More possibilities? (1) If you just want an array "accessor" without changing the array itself and without setting up a new array, then adapting Jesús Gabriel y Galán's post: class Object def nil_to( value ); self.nil? ? value : self ; end end a[5] = nil ; a[5].nil_to( 0 ) #=> 0 a[7] = false ; a[7].nil_to( 0 ) #=> false or even: class Array def at_with_nil_to(i, value); (obj = self[i]).nil? ? value : obj; end end (2) If you want to modify the array itself, instead of creating a new array, then adapting Rajinder Yadav's post you can do: arr.collect! { |obj| obj.nil? ? 0 : obj } or use "map!" which is a synonym for "collect!". Using "collect!" seems to be faster than using "each_with_index" and modifying the appropriate elements. Is that what people would expect? I ask because for similar things which modified arrays "in place" I used to use "each_with_index" type code until I understood what collect!/map! did.