tags:

views:

652

answers:

1

I believe this has been asked/answered before in a slightly different context, and I've seen answers to some examples somewhat similar to this - but nothing seems to exactly fit.

I have an array of email addresses:

@emails = ["[email protected]", "[email protected]"]

I want to create a hash out of this array, but it must look like this:

input_data = {:id => "#{id}", :session => "#{session}", 
              :newPropValues => [{:key => "OWNER_EMAILS", :value => "[email protected]"} , 
                                 {:key => "OWNER_EMAILS", :value => "[email protected]"}]

I think the Array of Hash inside of the hash is throwing me off. But I've played around with inject, update, merge, collect, map and have had no luck generating this type of dynamic hash that needs to be created based on how many entries in the @emails Array.

Does anyone have any suggestions on how to pull this off?

+4  A: 

So basically your question is like this:

having this array:

emails = ["[email protected]", "[email protected]", ....]

You want an array of hashes like this:

output = [{:key => "OWNER_EMAILS", :value => "[email protected]"},{:key => "OWNER_EMAILS", :value => "[email protected]"}, ...]

One solution would be:

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

Update: of course we can do it this way:

emails.map {|email| {:key => "OWNER_EMAILS", :value => email} }
khelll
inject is definitely the best solution
Matt Briggs
Ah ha! so that is how I would inject! This helps me a lot .. It not only solves my problem, but makes me understand inject a bit better. Thank you!
Indeed inject or map_reduce in other languages is a cool way to iterate a collection + apply some operation on all it's elements and moving the partial result to successor elements while iterating.
khelll
Excuse my ignorance, but what's wrong with `emails.map {|email| {:key => "OWNER_EMAILS", :value => email} }`?
sepp2k
@sepp2k you are a real Guru ;), using #map will work of course, but I wanted to show other use of inject :D Thanks!
khelll
Of course, and I played around with #map for awhile - I was over-complicating the solution that's for sure.