Hunter McMillen
Hunter McMillen

Reputation: 61512

How can I group data from one array based on parallel values in another?

I am extracting data from a database and storing it in two arrays, one array contains the labels for the data, and the other contains the data. I need to manipulate the arrays in a way so that I have one label for each set of data.

Arrays right now

labels - [Development, Development, Development, Development, Release, Release, Release, Release, ...]

data - [DevData1, DevData2, DevData3, DevData4, RelData1, RelData2, RelData3, RelData4, ...]

I only need only label per set of data, but I want to break the data into segments to correspond with the single labels. There are four label/data pairs because this is data from the last four months. I would just split the array on every 4th element, but some of the months dont have entries. So I need a better way to split the data.

Any ideas would be great. Thanks.

Upvotes: 2

Views: 143

Answers (3)

mu is too short
mu is too short

Reputation: 434635

You could combine the separate arrays into a hash without too much effort:

a = [:Development, :Development, :Development, :Development, :Release, :Release, :Release, :Release]
b = [:DevData1, :DevData2, :DevData3, :DevData4, :RelData1, :RelData2, :RelData3, :RelData4]
h = Hash.new { |h, k| h[k] = [ ] }
a.each_with_index { |e, i| h[e].push(b[i]) }
# h is now {:Development=>[:DevData1, :DevData2, :DevData3, :DevData4], :Release=>[:RelData1, :RelData2, :RelData3, :RelData4]}

Just make sure you use Hash.new { |h,k| h[k] = [ ] } and not Hash.new([]) or you'll end up with two hash entries pointing at the same array and that will just make a mess of things.

References:

Upvotes: 4

J Lundberg
J Lundberg

Reputation: 2363

A not very ruby solution to this would be just to loop through both of the arrays with an iterator and use them as you need them.

Upvotes: 1

Dylan Markow
Dylan Markow

Reputation: 124419

Why not just store it as a hash?

h = {"Development" => [DevData1, DevData2...], "Release" => [RelData1...]}

Then you could access "Development" data like this:

h["Development"]
# => [DevData1, DevData2...]

Upvotes: 1

Related Questions