How to map a Ruby hash?

671 views Asked by At

Is there a better way to map a Ruby hash? I want to iterate over each pair and collect the values. Perhaps using tap?

hash = { a:1, b:2 }

output = hash.to_a.map do |one_pair|
  k = one_pair.first
  v = one_pair.last  
  "#{ k }=#{ v*2 }"
end

>> [
  [0] "a=2",
  [1] "b=4"
]
3

There are 3 answers

0
Dan Grahn On BEST ANSWER

Ruby's hash includes the Enumerable module which includes the map function.

hash = {a:1, b:2}
hash.map { |k, v| "#{k}=#{v * 2}" }

Enumerable#map | RubyDocs

0
user229044 On

Err, yes, with map, invoked directly on the hash:

{ a:1, b:2 }.map { |k,v| "#{k}=#{v*2}" } # => [ 'a=2', 'b=4' ]
0
Arup Rakshit On
hash = { a:1, b:2 }
hash.map{|k,v| [k,v*2]* '='}
# => ["a=2", "b=4"]