From: Rick DeNatale Date: 2007-05-04T04:03:03+09:00 Subject: Re: Array to Hash On 5/3/07, james.d.masters@gmail.com wrote: > On May 3, 10:17 am, s...@seebs.net (Peter Seebach) wrote: > > In message , Chris Browne writes: > > > > >array = [ nil, "b", nil, nil, nil , "f", "g", nil, nil, "j"] > > >hash = {} > > >array.each_with_index { |value, index| hash[index] = value unless ! value } > > >puts hash.inspect > > > > My code was very similar to this. > > > > 5 quatloos to the first person to find a hypothetical case where this code > > produces the wrong answer. > > When values are false. Replace condition from "! value" to > "value.nil?". Not necessarily the simplest thing that could possibly work. If you're only interested in the hash being 'equivalent' to the array, a simpler approach works: array.each_with_index { |value, index| hash[index] = value } Sure the array will have entries with keys mapping to nil values, but you can't tell the difference with [] alone. If you want other aspects of the hash then yes, go ahead and supress nil values -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/ IPMS/USA Region 12 Coordinator http://ipmsr12.denhaven2.com/ Visit the Project Mercury Wiki Site http://www.mercuryspacecraft.com/