Ruby 1.9: turn these 4 arrays into hash of key/value pairs

Posted by randombits on Stack Overflow See other posts from Stack Overflow or by randombits
Published on 2010-05-06T00:48:50Z Indexed on 2010/05/06 0:58 UTC
Read the original article Hit count: 178

Filed under:

I have four arrays that are coming in from the client. Let's say that there is an array of names, birth dates, favorite color and location. The idea is I want a hash later where each name will have a hash with respective attributes:

Example date coming from the client:

[name0, name1, name2, name3]
[loc0, loc1]
[favcololor0, favcolor1]
[bd0, bd1, bd2, bd3, bd4, bd5]

Output I'd like to achieve:

name0 => { location => loc0, favcolor => favcolor0, bd => bd0 }
name1 => { location => loc1, favcolor => favcolor1, bd => bd1 }
name2 => { location => nil, favcolor => nil, bd => bd2 }
name3 => { location => nil, favcolor => nil, bd => bd3 }

I want to have an array at the end of the day where I can iterate and work on each particular person hash.

There need not be an equivalent number of values in each array. Meaning, names are required.. and I might receive 5 of them, but I only might receive 3 birth dates, 2 favorite colors and 1 location. Every missing value will result in a nil.

How does one make that kind of data structure with Ruby 1.9?

© Stack Overflow or respective owner

Related posts about ruby