Reputation: 45941
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"
]
Upvotes: 0
Views: 689
Reputation: 9424
Ruby's hash includes the Enumerable module which includes the map
function.
hash = {a:1, b:2}
hash.map { |k, v| "#{k}=#{v * 2}" }
Upvotes: 5
Reputation: 118299
hash = { a:1, b:2 }
hash.map{|k,v| [k,v*2]* '='}
# => ["a=2", "b=4"]
Upvotes: 1
Reputation: 239521
Err, yes, with map
, invoked directly on the hash:
{ a:1, b:2 }.map { |k,v| "#{k}=#{v*2}" } # => [ 'a=2', 'b=4' ]
Upvotes: 3