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

后端 未结 7 1884
刺人心
刺人心 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:48

    If you want to check if an object is within in array by checking an attribute on the object, you can use any? and pass a block that evaluates to true or false:

    unless @suggested_horses.any? {|h| h.id == horse.id }
      @suggested_horses << horse
    end
    

提交回复
热议问题