1

I've read through quite a few of posts, but none seem to do just this, which is a bit tricky.

Say I have a hash that contains an array as one of its values.

hash = {
  :a => 'one', 
  :arr => [
    {:id => 'ten',    :amount => 10, :b => 'two'}, 
    {:id => 'twenty', :amount => 20, :b => 'two'},
    {:id => 'apple',  :amount => 7,  :b => 'applesauce'}
  ], 
  :c => 3
}

I want to convert this to an array of hashes (which would be of the size of the contained array), as follows:

# => [
  {:a => 'one', :id => 'ten',    :amount => 10, :b => 'two',        :c => 3},
  {:a => 'one', :id => 'twenty', :amount => 20, :b => 'two',        :c => 3},
  {:a => 'one', :id => 'apple',  :amount => 7,  :b => 'applesauce', :c => 3}
]

The conversion should maintain whatever key/value pairs are inside and outside the array, and ideally I could pass in the key of the array to ask it perform the action:

flatten_hash_array(hash, :arr)

I realize that the Ruby flatten in the Array class is not what we need. Grasping for a verb! Any help would be appreciated.

1 Answer 1

5

This should do the job, barring validity checks.

def flatten_hash_array(hash, key)
  hash[key].map {|entry| entry.merge(hash.reject {|k| k == key})}
end
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! the hash.reject block just needs to be passed k,v and it works like a charm. Thanks! def flatten_hash_array(hash, key) hash[key].map {|entry| entry.merge(hash.reject {|k,v| k == key})} end
Hmm, must be a 1.8 / 1.9 difference - my Ruby accepts hash.reject {|k|}, even though there are two params available. But hey - glad it works for you.

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.