开发者

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

开发者 https://www.devze.com 2023-03-25 12:18 出处:网络
I am extracting data from a database and storing it in two arrays, one ar开发者_运维技巧ray contains the labels for the data, and the other contains the data. I need to manipulate the arrays in a way

I am extracting data from a database and storing it in two arrays, one ar开发者_运维技巧ray 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.


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:

  • Hash with a default proc
  • each_with_index
  • push


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...]


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消