# Find elements of an array on another

**URL:** <https://www.ruby-forum.com/t/find-elements-of-an-array-on-another/113699>\
**Category:** Rails\
**Created:** [September 4, 2007, 3:22am UTC](https://www.ruby-forum.com/t/find-elements-of-an-array-on-another/113699 "2007-09-04T03:22:34Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Carlos\_Fonseca](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/bc8723/32.png) [@Carlos\_Fonseca](https://www.ruby-forum.com/u/Carlos_Fonseca)\
**Post date:** [September 4, 2007, 3:22am UTC](https://www.ruby-forum.com/t/find-elements-of-an-array-on-another/113699/1 "2007-09-04T03:22:34Z")

</div>

Hi

I have two arrays of items, and I want to cycle one and see if its  
items are on the other one, but I can’t find out how to do it… I’ve  
been trying to do something like this

@a = Item.find(:all, :conditions =\> “name LIKE ‘%a%’”)  
@b = Item.find(:all, :conditions =\> “name LIKE ‘%b%’”)

for i in @a  
if @a.find(i)  
do stuff  
else  
do something else  
end  
end

and I keep getting a “no block given” error on the if line… if @a is  
an array, i can search using find, and I believe I can use the  
object… I’ve tried a find\_by\_id but I got an “undefined method for  
array” error…

Any ideas?  
Thanks  
Carlos Fonseca

---

<div class="post-metadata">

**Author:** ![Carlos\_Fonseca](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/bc8723/32.png) [@Carlos\_Fonseca](https://www.ruby-forum.com/u/Carlos_Fonseca)\
**Post date:** [September 4, 2007, 4:37am UTC](https://www.ruby-forum.com/t/find-elements-of-an-array-on-another/113699/2 "2007-09-04T04:37:44Z")

</div>

If I’m understanding you correctly, you’re trying to check if each  
element in array @a is present in array @b and act accordingly,  
something like:

@a.each do |item|  
if @b.include? item  
[do stuff]  
else  
[do other stuff]  
end  
end

It would be more performant (but less readable) to do something like  
this:

( @a & @b ).each do |item|  
[do stuff]  
end

( @a - @b ).each do |item|  
[do other stuff]  
end

---

<div class="post-metadata">

**Author:** ![Carlos\_Fonseca](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/bc8723/32.png) [@Carlos\_Fonseca](https://www.ruby-forum.com/u/Carlos_Fonseca)\
**Post date:** [September 4, 2007, 12:57pm UTC](https://www.ruby-forum.com/t/find-elements-of-an-array-on-another/113699/3 "2007-09-04T12:57:43Z")

</div>

I tried the .include?( item ) but it didn’t work back then and I  
forgot to mention it yesterday. No idea why it wasn’t working but now  
it works! Thanks 😃
