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

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

    Array's include?method accepts any object, not just a string. This should work:

    @suggested_horses = [] 
    @suggested_horses << Horse.first(:offset => rand(Horse.count)) 
    while @suggested_horses.length < 8 
      horse = Horse.first(:offset => rand(Horse.count)) 
      @suggested_horses << horse unless @suggested_horses.include?(horse)
    end
    
    • Array#include? documentation
    0 讨论(0)
提交回复
热议问题