[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

Re: Array to Hash

seebs

5/3/2007 5:17:00 PM

In message <D5AF5C55-270A-4E23-899D-11EAE7ED19EA@rallydev.com>, 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.

-s

4 Answers

james.d.masters

5/3/2007 5:42:00 PM

0

On May 3, 10:17 am, s...@seebs.net (Peter Seebach) wrote:
> In message <D5AF5C55-270A-4E23-899D-11EAE7ED1...@rallydev.com>, 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?".

james.d.masters

5/3/2007 5:44:00 PM

0

On May 3, 10:41 am, james.d.mast...@gmail.com wrote:
> When values are false. Replace condition from "! value" to
> "value.nil?".

Spoke too soon... also when duplicate array items exist...

Rick DeNatale

5/3/2007 7:03:00 PM

0

On 5/3/07, james.d.masters@gmail.com <james.d.masters@gmail.com> wrote:
> On May 3, 10:17 am, s...@seebs.net (Peter Seebach) wrote:
> > In message <D5AF5C55-270A-4E23-899D-11EAE7ED1...@rallydev.com>, 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.denh...

IPMS/USA Region 12 Coordinator
http://ipmsr12.denh...

Visit the Project Mercury Wiki Site
http://www.mercuryspace...

Rick DeNatale

5/3/2007 7:05:00 PM

0

On 5/3/07, Rick DeNatale <rick.denatale@gmail.com> wrote:

> Sure the array will have entries with keys mapping to nil values,
sub("array","hash")

--
Rick DeNatale

My blog on Ruby
http://talklikeaduck.denh...