如何比较数组RUBY中的对象

时间:2017-01-06 13:22:23

标签: ruby-on-rails ruby

如何在ruby中比较具有相同参数的对象?如何定义elsif部分?

def compare
    array_of_items = @items.map(&:object_id)
    if array_of_items.uniq.size == array_of_items.size #array has only uniq vlaues - it's not possible to duplicate object - good!
      return
    elsif
      #the comparision of objects with the same object_id by other param (i.e. date_of_lease param). The part I can not formulate
    else
      errors.add('It is not possible to purchase many times one item with the same values')
    end
  end

4 个答案:

答案 0 :(得分:0)

您可以使用Enumerable#group_by,例如

elsif @items.group_by(&:date_of_lease).count == array_of_items.size

答案 1 :(得分:0)

据我了解,我猜你想比较两个具有相同object_id的对象。

same_objects = @items.select { | element |
        if array_of_items.count(element.object_id) > 1 do 
           # Duplicate object
        end
}

答案 2 :(得分:0)

我不知道其他Ruby实现如何,但在MRI Object#object_id中为每个对象返回唯一(内存中对象的整数表示)值。如果您尝试重新定义它,您将收到警告:

class Object
  def object_id
    'a'
  end
end
#=> warning: redefining `object_id' may cause serious problems
:object_id

答案 3 :(得分:0)

首先,由于这被标记为rails,这不是您可以使用内置验证解决的类型吗?

 validates_uniqueness_of :date_of_lease, scope: :object_id

我不知道您的实现,但如果您使用数据库的主键,则可能甚至不需要该范围。

否则,假设你已经覆盖了ruby object_id,那么两个对象可以有相同的id(¿?)我只能想到一些复杂的东西:

 def compare
   duplicate_items = @items.group_by(&:object_id).select { |k,v| v.size > 1}
   if duplicate_items.keys.empty? 
     return
   elsif duplicate_items.select{|k,v| v.group_by(&:date_of_lease).count != v.count}.empty?
     # There are no duplicate object ids that also have duplicate 
     # dates of lease between themselves
   else
      errors.add('It is not possible to purchase many times one item with the same values')
   end
 end

检查是否必须在具有重复项的同一items数组中处理具有相同租约日期的不同对象ID的情况,该数组应该是有效的。例如:Item id 1, date 12, Item id 1, date 13, item id 2, date 12应该有效。