I have three arrays.
My main list contains a mix of different entities which are verified in a DB:
ab = ["a:555", "b:222", "a:333", "b:777", "a:777", "a:999", "b:111"]
I have two more arrays of a
and b
entities separated, but ordered (some are missing):
# notice that some of the items from the initial list are missing, but the order is preserved!
a = [{id}, "a:777", "a:999"]
b = ["b:222", "b:111"]
What is an efficient way to merge a
and b
in array c
preserving the order in ab
where the items are present? My expected result from the procedure is:
c = ["a:555", "b:222", "a:777", "a:999", "b:111"]
I'm a Ruby newbie and everything I came up with is utterly ugly.
Edit:
I did know it matters, and would be confusing, but a
and b
are complex objects (AR) that represent the strings in ab
. To clarify with my code:
ab = ["a:555", "b:222", "a:333", "b:777", "a:777", "a:999", "b:111"]
a = [{:id => 555}, {:id => 777}, {:id => 999}]
b = [{:id => 222}, {:id => 111}]
c = []
ab.each { |item|
parts = item.split(":")
if parts[0] == "a"
if a[0][:id].to_s() == parts[1]
c << a.shift()
end
else
if b[0][:id].to_s() == parts[1]
c << b.shift()
end
end
}
puts c