From: Intransition Date: 2011-06-04T21:35:47+09:00 Subject: Re: Best way to replace hash keys On Jun 3, 10:27 am, Alex Allmont 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.  Another approach would to simply rebuild a whole new 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.