Changing every value in a hash in Ruby

theReverseFlick picture theReverseFlick · Mar 4, 2011 · Viewed 143.8k times · Source

I want to change every value in a hash so as to add '%' before and after the value so

{ :a=>'a' , :b=>'b' }

must be changed to

{ :a=>'%a%' , :b=>'%b%' }

What's the best way to do this?

Answer

shock_one picture shock_one · Sep 4, 2014

In Ruby 2.1 and higher you can do

{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h