Find elements of an array on another

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

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

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 :smiley:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs