On Jun 3, 10:27=A0am, Alex Allmont <Alex.Allm... / 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> r=
eplace } pairs,
> =A0 # convert any String keys to a Regexp.
> =A0 newPairs =3D { }
> =A0 searchReplacePairs.delete_if do |search, replace|
> =A0 =A0 if search.class =3D=3D String
> =A0 =A0 =A0 newPairs[Regexp.new(search)] =3D replace
> =A0 =A0 end
> =A0 end
> =A0 searchReplacePairs.merge! newPairs

I'm not sure your example actually works, I think you'll end up with
both string AND regexp keys.

Here's an alternative:

  require 'facets/hash/rekey'

 =A0 searchReplacePairs.rekey! do |search, replace|
 =A0   search.class =3D=3D String ? Regexp.new(search) : search
 =A0 end

See http://rubydoc.info/github/rubyworks/facets/master/Hash#rekey-instance_=
method

It's one of my favorite core extensions.