On Jun 3, 10:27 ¨Βν¬ Αμεψ ΑμμνοξΌΑμεψ®Αμμν®®®ΐξατυςαμνοτιοξ®γονΎ
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 hash before merging them back into the original hash.  ¨Βξοτθες αππςοαγθ χουμτο σινπμω ςεβυιμχθομξεθασθ>
> # Contrived example: given searchReplacePairs hash of { search => replace } pairs,
> # convert any String keys to a Regexp.
> newPairs = { }
> searchReplacePairs.delete_if do |search, replace|
> if search.class == String
> newPairs[Regexp.new(search)] = replace
> end
> end
> 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'

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

See http://rubydoc.info/github/rubyworks/facets/master/Hash#rekey-instance_method

It's one of my favorite core extensions.