tvalent2
tvalent2

Reputation: 5009

Create array of individual hashes from one hash

Given a hash of key/value pairs, how can I turn that into an array of individual hashes for each key/value pair.

So for example, starting with:

{"hello"=>"bonjour", "goodbye"=>"au revoir"}

And turning that into:

[ {"hello" => "bonjour"}, {"goodbye" => "au revoir"} ]

I got that with the following but am wondering if there's an easier approach:

array = []
hash.each do |k,v|
  h = Hash.new
  h[k] = v
  array << h
end

Upvotes: 0

Views: 52

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118261

Do as below using Enumerable#map:

h = {"hello"=>"bonjour", "goodbye"=>"au revoir"}
h.map { |k,v| { k => v } }
# => [{"hello"=>"bonjour"}, {"goodbye"=>"au revoir"}]

Upvotes: 3

Related Questions