From: dblack@... Date: 2006-01-05T05:15:36+09:00 Subject: Re: Question on iterating a hash --8323328-498222878-1136405722=:22560 Content-Type: MULTIPART/MIXED; BOUNDARY="8323328-498222878-1136405722=:22560" This message is in MIME format. The first part should be readable text, while the remaining parts are likely unreadable without MIME-aware tools. --8323328-498222878-1136405722=:22560 Content-Type: TEXT/PLAIN; charset=X-UNKNOWN; format=flowed Content-Transfer-Encoding: QUOTED-PRINTABLE Hi -- On Thu, 5 Jan 2006, Simon Kr=F6ger wrote: > dblack@wobblini.net wrote: > >> Hi -- >>=20 >> On Thu, 5 Jan 2006, James Edward Gray II wrote: >>=20 >>> On Jan 4, 2006, at 12:46 PM, phil swenson wrote: >>>=20 >>>> I have a hash that looks like this : {"1"=3D>"0, "3"=3D"1", "45"=3D>"1= ", >>>> "101"=3D>"0"} >>>>=20 >>>> What I want is an array of all the keys that have hash values equal to >>>> "1" ["3","45"] in this case. >>>>=20 >>>> Yeah, i can just iterate the keys... but it seems like there is a "rub= y" >>>> way to do this. Any thoughts? >>>=20 >>>=20 >>>>> h =3D Hash[*%w{1 0 3 1 45 1 101 0}] >>>=20 >>> =3D> {"45"=3D>"1", "1"=3D>"0", "101"=3D>"0", "3"=3D>"1"} >>>=20 >>>>> h.select { |key, value| value =3D=3D "1" }.map { |key, value| key } >>>=20 >>> =3D> ["45", "3"] >>=20 >>=20 >> Wouldn't it be easier to iterate through the keys? I'm not sure why >> Phil didn't want to. (Phil?) >> >> h.keys.select {|k| h[k] =3D=3D 1} >>=20 >>=20 >> David > > Don't know, but here is another one: > > h.select{|k, v| v =3D=3D "1" }.transpose.first OK... but I'm still not getting why just "select"ing the ones you want isn't the best way. David --=20 David A. Black dblack@wobblini.net "Ruby for Rails", from Manning Publications, coming April 2006! http://www.manning.com/books/black --8323328-498222878-1136405722=:22560-- --8323328-498222878-1136405722=:22560--