Question

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"
]
Was it helpful?

Solution

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

OTHER TIPS

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

{ a:1, b:2 }.map { |k,v| "#{k}=#{v*2}" } # => [ 'a=2', 'b=4' ]
hash = { a:1, b:2 }
hash.map{|k,v| [k,v*2]* '='}
# => ["a=2", "b=4"]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top