0

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"
]
B Seven
  • 44,484
  • 66
  • 240
  • 385

3 Answers3

5

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

Dan Grahn
  • 9,044
  • 4
  • 37
  • 74
3

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

{ a:1, b:2 }.map { |k,v| "#{k}=#{v*2}" } # => [ 'a=2', 'b=4' ]
user229044
  • 232,980
  • 40
  • 330
  • 338
1
hash = { a:1, b:2 }
hash.map{|k,v| [k,v*2]* '='}
# => ["a=2", "b=4"]
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317