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

Viewed 171213

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 included (exists) in it?

I tried something like:

@suggested_horses = []
  @suggested_horses << Horse.find(:first,:offset=>rand(Horse.count))
  while @suggested_horses.length < 8
    horse = Horse.find(:first,:offset=>rand(Horse.count))
    unless @suggested_horses.exists?(horse.id)
       @suggested_horses<< horse
    end
  end

I also tried with include? but I saw it was for strings only. With exists? I get the following error:

undefined method `exists?' for #<Array:0xc11c0b8>

So the question is how can I check if my array already has a "horse" included so that I don't fill it with the same horse?

7 Answers

An alternative to horses.include? new_horse is new_horse.in? horses.

I don't think there's much (any?) difference under the hood, but sometimes it reads better that way. Particularly if you want the first term to explain a bit more of what is going on before reading the entire statement. For example, this:

[403, 404, 503].include? http_status 

...is not as readable as:

http_status.in? [403, 404, 503]
Related