Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing every value in a hash in Ruby

Tags:

ruby

hash

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?

like image 635
theReverseFlick Avatar asked Mar 04 '11 02:03

theReverseFlick


People also ask

How do you update a value in a hash Ruby?

Modifying hashes in Ruby: Hash can be modified by adding or deleting a key value/pair in an already existing hash. Also, you can change the existing value of key in the hash.

How do I iterate a hash in Ruby?

Iterating over a Hash You can use the each method to iterate over all the elements in a Hash. However unlike Array#each , when you iterate over a Hash using each , it passes two values to the block: the key and the value of each element.


1 Answers

In Ruby 2.1 and higher you can do

{ a: 'a', b: 'b' }.map { |k, str| [k, "%#{str}%"] }.to_h 
like image 149
shock_one Avatar answered Oct 11 '22 20:10

shock_one