Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 543
necker Avatar asked Jul 27 '10 13:07

necker


People also ask

How do you check if an array is an array of objects?

isArray() method is used to check if an object is an array. The Array. isArray() method returns true if an object is an array, otherwise returns false .

Can an array contain objects?

Storing Objects in an arrayYes, since objects are also considered as datatypes (reference) in Java, you can create an array of the type of a particular class and, populate it with instances of that class.


1 Answers

Arrays in Ruby don't have exists? method, but they have an include? method as described in the docs. Something like

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

should work out of box.

like image 154
Tomasz Cudziło Avatar answered Sep 29 '22 21:09

Tomasz Cudziło