0

I need to modify a hash of hash and convert it in a hash of array.

I also need to add a new key value.

This is my current hash:

{ "132552" => {
           "name" => "Paul",
           "id" => 53
         },
"22478" => {
          "name" => "Peter",
           "id" => 55
        }
}

I expect the output to be like this:

[
  {
      "person_id": "132552",
      "name" => "Paul",
      "id" => 53
   },
   {
      "person_id": "22478",
      "name" => "Peter",
      "id" => 55
   }
]

3 Answers 3

2

You could map with Enumerable#map to hash values merging (Hash#merge) the new pairs:

original_hash.map { |k,v| v.merge({ "person_id" => k }) }
#=> [{"name"=>"Paul", "id"=>53, "person_id"=>"132552"}, {"name"=>"Peter", "id"=>55, "person_id"=>"22478"}]
Sign up to request clarification or add additional context in comments.

Comments

0

Probably not the best solution but the following should work (considering h is your hash):

@h.each do |key,value|
  value["person_id"] = key
end

@array = []

@h.each do |key, value|
  @array << value
end

Comments

0

This is a perfect fit for Enumerable#each_with_object.

output = input.each_with_object([]) do |(person_id, values), array|
  array << values.merge("person_id" => person_id)
end

This method takes an arbitrary object for our initial state (here an array), iterate the collection (our hash) with a block. The initial object is yield as second argument of the block. At each iteration we're populating the array as we want. At the end of the block this object is returned, in output variable in my example.

Note that in my example, I destructure the hash into (person_id, values) : each entry of an hash can be destructed as (key, values) into block/method arguments.

Enumerable#each_with_object

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.