From: "Matthew K. Williams" Date: 2009-10-23T02:25:53+09:00 Subject: Re: convert/replace a value of nil with 0? --8323329-1806310257-1256232732=:10902 Content-Type: MULTIPART/MIXED; BOUNDARY="8323329-1806310257-1256232732=:10902" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --8323329-1806310257-1256232732=:10902 Content-Type: TEXT/PLAIN; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE On Fri, 23 Oct 2009, [ISO-8859-1] Jes=FAs Gabriel y Gal=E1n wrote: > On Thu, Oct 22, 2009 at 6:07 PM, Paul Smith wro= te: >> 2009/10/22 Jes=FAs Gabriel y Gal=E1n : >>> On Thu, Oct 22, 2009 at 5:24 PM, Mmcolli00 Mom = wrote: >>>> Do you know how I can convert or replace any value that gets back a >>>> 'nil' to 0? >>>> >>>> For instance, the myArrayVal[0] may or may not contain a number and I >>>> want the code to default to 0 if a nil is returned. I have not found a= ny >>>> documentation on this. >>> >>> irb(main):001:0> array =3D [] >>> =3D> [] >>> irb(main):002:0> value =3D array[0] || 0 >>> =3D> 0 >>> irb(main):003:0> value >>> =3D> 0 >>> >>> Hope this helps, >> >> Though that will of course convert false too. > > Sure, if you can have in the array things that are not numbers I think > to_i as Gregory suggested should work in general. Or you can do it > more explicitly like this: > > value =3D array[0].nil? ? 0 : array[0] > Or, being very evil...... class Array idx =3D self.instance_method(:[]) define_method(:[]) do |x| n=3Didx.bind(self).call(x) return n.nil? ? 0 : n end end (this is based off of=20 http://blog.jayfields.com/2006/12/ruby-alias-method-alternative.html ) Matt --8323329-1806310257-1256232732=:10902-- --8323329-1806310257-1256232732=:10902--