January 26, 2012
Using Enumerable::inject to modify a hash

rubyquicktips:

Ever wanted to modify the keys and values of a Hash? Enumerable::inject has you covered.

Try this snippet from Stack Overflow:

my_hash = { a: 'foo', b: 'bar' }
# => {:a=>"foo", :b=>"bar"}
a_new_hash = my_hash.inject({}) { |h, (k, v)| h[k.upcase] = v.upcase; h }
# => {:A=>"FOO", :B=>"BAR"}

  1. haru012 reblogged this from rubyquicktips
  2. rubyloveinfo reblogged this from rubyquicktips
  3. rubyquicktips posted this