On Fri, Jun 3, 2011 at 11:27 PM, Alex Allmont
<Alex.Allmont / naturalmotion.com> wrote:
> What is the most optimal and neatest way to replace keys in a hash given =
a particular condition?
>
> I'm currently using delete_if and putting replacement values into a new h=
ash before merging them back into the original hash. =A0Another approach wo=
uld to simply rebuild a whole new hash.
>
> =A0# Contrived example: given searchReplacePairs hash of { search =3D> re=
place } pairs,
> =A0# convert any String keys to a Regexp.
> =A0newPairs =3D { }
> =A0searchReplacePairs.delete_if do |search, replace|
> =A0 =A0if search.class =3D=3D String
> =A0 =A0 =A0newPairs[Regexp.new(search)] =3D replace
> =A0 =A0end
> =A0end
> =A0searchReplacePairs.merge! newPairs
>
> Many thanks,
> Alex
>
>
>

I won't claim this is the best way but it may be worth a look.
Is it doing what you want or did I misunderstand?


a =3D {"ONE"=3D>"1",2=3D>"2","THREE"=3D>"3"}

t =3D a.to_a.transpose
b =3D Hash[*(t[0].map{|x| x.class=3D=3DString ? Regexp.new(x) :x}.zip(t[1])=
).flatten]
p b #>   {/ONE/=3D>"1", 2=3D>"2", /THREE/=3D>"3"}




Harry