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 = ["test@test.com", "test2@test2.com"]
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 => "test@test.com"} ,
{:key => "OWNER_EMAILS", :value => "test2@test2.com"}]
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?
So basically your question is like this:
having this array:
emails = ["test@test.com", "test2@test2.com", ....]
You want an array of hashes like this:
output = [{:key => "OWNER_EMAILS", :value => "test@test.com"},{:key => "OWNER_EMAILS", :value => "test2@test2.com"}, ...]
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} }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.