9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

rubyでハッシュの配列を指定したキーでマージするメソッドがあると便利

Posted at

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}]
9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?