From: Harry Kakueki Date: 2011-06-04T18:06:15+09:00 Subject: Re: Best way to replace hash keys On Fri, Jun 3, 2011 at 11:27 PM, 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 > > 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 = {"ONE"=>"1",2=>"2","THREE"=>"3"} t = a.to_a.transpose b = Hash[*(t[0].map{|x| x.class==String ? Regexp.new(x) :x}.zip(t[1])).flatten] p b #> {/ONE/=>"1", 2=>"2", /THREE/=>"3"} Harry