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" ] 

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.