且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除"重复对象和QUOT;

更新时间:2023-02-15 20:31:41

 看到= []
#sort通过创建日期和迭代
collection.sort({| A,B | a.created_at< => b.created_at})。每做| OBJ |
  如果seen.map(安培;:名).INCLUDE?如果该名称已被视为已经obj.name #check
    obj.destroy!
  其他
    可见<< OBJ#如果不是,将其添加到阵列可见
  结束
结束
 

如果希望做的工作。

Let's say I have an array of objects from the same class, with two attributes of concern here: name and created_at.

How do I find objects with the same name (considered dups) in the array, and then delete the duplicate record in the database. The object with the most-recent created_at date, however, is the one that must be deleted.

seen = []
#sort by created date and iterate
collection.sort({|a,b| a.created_at <=> b.created_at}).each do |obj| 
  if seen.map(&:name).include? obj.name #check if the name has been seen already
    obj.destroy!
  else
    seen << obj #if not, add it to the seen array
  end
end

Should do the job hopefully.