How do I check to see if my array includes an object?

后端 未结 7 1891
刺人心
刺人心 2020-12-04 23:19

I have an array @horses = [] that I fill with some random horses.

How can I check if my @horses array includes a horse that is already incl

7条回答
  •  不知归路
    2020-12-04 23:31

    #include? should work, it works for general objects, not only strings. Your problem in example code is this test:

    unless @suggested_horses.exists?(horse.id)
      @suggested_horses<< horse
    end
    

    (even assuming using #include?). You try to search for specific object, not for id. So it should be like this:

    unless @suggested_horses.include?(horse)
      @suggested_horses << horse
    end
    

    ActiveRecord has redefined comparision operator for objects to take a look only for its state (new/created) and id

提交回复
热议问题