我有三个数组。
我的主列表包含在数据库中验证的不同实体的组合:
ab = ["a:555", "b:222", "a:333", "b:777", "a:777", "a:999", "b:111"]
我还有两个数组a
和b
实体分开,但有序(有些缺失):
# 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"]
什么是合并a
和b
在数组中保留项目存在c
顺序的有效方法?ab
我对该程序的预期结果是:
c = ["a:555", "b:222", "a:777", "a:999", "b:111"]
我是一个 Ruby 新手,我想出的一切都非常丑陋。
编辑:
我确实知道这很重要,并且会令人困惑,但是a
并且b
是表示ab
. 为了澄清我的代码:
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