Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easily map over Hash like Array#map

Tags:

ruby

hash

Sometimes I want to map over a collection. If it's an array it's easy:

foo = [1,2,3]
foo.map {|v| v + 1}
#=> [2, 3, 4]

But a hash doesn't work the same way:

bar = {a: 1, b: 2, c: 3}
bar.map{|k,v| v+1}
#=> [2, 3, 4]

What I'd really like is something like:

bar = {a: 1, b: 2, c: 3}
bar.baz{|k,v| v+1}
#=> {:a=>2, :b=>3, :c=>4}

where Hash#baz is some method. Is there an easy way to get a "map-like" experience for a hash?

like image 727
mbigras Avatar asked Feb 09 '17 19:02

mbigras


1 Answers

In Ruby 2.4 you can use the built-in Hash#transform_values:

bar = {a: 1, b: 2, c: 3}
# => {:a=>1, :b=>2, :c=>3}
bar.transform_values {|v| v+1 }
# => {:a=>2, :b=>3, :c=>4}
like image 125
Jordan Running Avatar answered Oct 10 '22 06:10

Jordan Running