Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I merge and order multiple lists together using Ruby?

Tags:

ruby

I have 2 lists that have dates and data. Each list is in the proper order as noted by the sequence number. Now I need to merge the 2 lists together and keep everything in the correct order.

For example:

List A
20101001 A data 1 seq1
20101001 A data 2 seq2
20101005 A data 3 seq3

List B
20101001 B data 1 seq1
20101003 B data 2 seq2

etc...

I need the new list to look like this:

20101001 A data 1 seq1
20101001 A data 2 seq2
20101001 B data 1 seq3
20101003 B data 2 seq4
20101005 A data 3 seq5

2 things that I thought of is merging the lists together and applying the sequence number prior to inserting them into a db or I can insert them into the db with the current sequence and pull them back out again to merge them together, but that seems like an extra step and kludgy.

Any ideas on the best way to go about this?

like image 794
cswebgrl Avatar asked Oct 11 '10 16:10

cswebgrl


1 Answers

Assuming your lists are in Ruby Arrays, and the objects in the lists have attributes defined (such as obj.sequence_number), one way to merge and sort the lists would be:

First merge the lists as a union:

@merged_list = @list_a | @list_b

Then sort the merged_list with the appropriate sorting rule:

@merged_list.sort! {|a, b| a.date <=> b.date # or whatever your sorting rule is... }

Edit:

Once the merged array is sorted, you can re-define the sequence_number:

@merged_list.each_with_index {|obj, index| obj.sequence_number = "seq#{index+1}"}

Edit:

Same thing applies if your objects in the lists are themselves just simple arrays:

@merged_list.sort! {|a, b| a[0] <=> b[0] # or whatever your sorting rule is... }
@merged_list.each_with_index {|obj, index| obj[2] = "seq#{index+1}"}
like image 184
Dave Sims Avatar answered Sep 28 '22 00:09

Dave Sims