DB分割等でjoinできない時など、ruby側でDBのデータをマージしないといけない時によく使います
array.rb
class Array
def merge_by_index(other,index1='id',index2=nil)
index2 = index1 if index2.nil?
merge_hash = {}
self.map {|data| merge_hash[data[index1]] = data}
other.each do |data|
key = data[index2]
data[index1] = key if index1 != index2
data.delete(index2) if index1 != index2
merge_hash[key] = (merge_hash[key] == nil) ? data : merge_hash[key].merge(data)
end
return merge_hash.values
end
end
indexをキーに配列をマージする
a = [
{'id' => 1,'val' => 1},
{'id' => 2,'val' => 1}
]
b = [
{'id' => 2,'val' => 2},
{'id' => 3,'val' => 2}
]
p a.merge_by_index(b)
#=> [{"id"=>1, "val"=>1}, {"id"=>2, "val"=>2}, {"id"=>3, "val"=>2}]
joinする
a = [
{'id' => 1,'val' => 1}
]
b = [
{'id' => 1,'name' => 'hoge'}
]
p a.merge_by_index(b)
#=> [{"id"=>1, "val"=>1, "name"=>"hoge"}]
indexを指定する(デフォルトは'id')
a = [
{'user_id' => 1,'val' => 1}
]
b = [
{'user_id' => 1,'score' => 100}
]
p a.merge_by_index(b,'user_id')
#=> [{"user_id"=>1, "val"=>1, "score"=>100}]
キーの名前が違う配列同士でマージする
a = [
{'id' => 1,'val' => 1}
]
b = [
{'user_id' => 1,'score' => 100}
]
p a.merge_by_index(b,'id','user_id')
#=> [{"id"=>1, "val"=>1, "score"=>100}]