A
Alex Allmont
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 has=
h before merging them back into the original hash. Another approach would =
to simply rebuild a whole new hash.
# Contrived example: given searchReplacePairs hash of { search =3D> repla=
ce } pairs,
# convert any String keys to a Regexp.
newPairs =3D { }
searchReplacePairs.delete_if do |search, replace|=20
if search.class =3D=3D String
newPairs[Regexp.new(search)] =3D replace
end
end
searchReplacePairs.merge! newPairs
Many thanks,
Alex
particular condition?
I'm currently using delete_if and putting replacement values into a new has=
h before merging them back into the original hash. Another approach would =
to simply rebuild a whole new hash.
# Contrived example: given searchReplacePairs hash of { search =3D> repla=
ce } pairs,
# convert any String keys to a Regexp.
newPairs =3D { }
searchReplacePairs.delete_if do |search, replace|=20
if search.class =3D=3D String
newPairs[Regexp.new(search)] =3D replace
end
end
searchReplacePairs.merge! newPairs
Many thanks,
Alex