Ruby: Create a hash with default keys + array values

I believe that this was asked / answered earlier in a slightly different context, and I saw answers to some examples, somewhat similar to this, but nothing of the kind fits.

I have an array of email addresses:

@emails = [" test@test.com ", " test2@test2.com "] 

I want to create a hash from this array, but it should look like this:

 input_data = {:id => "#{id}", :session => "#{session}", :newPropValues => [{:key => "OWNER_EMAILS", :value => " test@test.com "} , {:key => "OWNER_EMAILS", :value => " test2@test2.com "}] 

I think the Array of Hash inside the hash throws me away. But I played with inject , update , merge , collect , map and was not lucky to create a dynamic hash of this type, which needs to be created based on how many entries in the @emails Array.

Does anyone have any suggestions on how to do this?

+4
source share
1 answer

So basically your question is this:

with this array:

 emails = [" test@test.com ", " test2@test2.com ", ....] 

You need an array of hashes, for example:

 output = [{:key => "OWNER_EMAILS", :value => " test@test.com "},{:key => "OWNER_EMAILS", :value => " test2@test2.com "}, ...] 

One solution:

 emails.inject([]){|result,email| result << {:key => "OWNER_EMAILS", :value => email} } 

Update: of course we can do it like this:

 emails.map {|email| {:key => "OWNER_EMAILS", :value => email} } 
+8
source

All Articles