19

I want to perform an if condition where, if linkedpub.LPU_ID is found in an array of values(@associated_linked_pub), do some action.

I tried the following but the syntax is not correct.

Any suggestion is most welcomed..Thanks a lot

<% for linkedpub in Linkedpub.find(:all) %>
   <% if linkedpub.LPU_ID IN @associated_linked_pub  %>
       # do action
   <%end%>
<%end%>
ardavis
  • 9,842
  • 12
  • 58
  • 112
tanya
  • 2,925
  • 7
  • 32
  • 49
  • possible duplicate of [check if value exists in array in Ruby](http://stackoverflow.com/questions/1986386/check-if-value-exists-in-array-in-ruby) – Mat Jun 14 '11 at 21:01

4 Answers4

39

You can use Array#include?

So...

if @associated_linked_pub.include? linkedpub.LPU_ID
  ...

Edit:

If @associated_linked_pub is a list of ActiveRecord objects then try this instead:

if @associated_linked_pub.map{|a| a.id}.include? linkedpub.LPU_ID
  ...

Edit:

Looking at your question in more detail, it looks like what you are doing is VERY inefficient and unscalable. Instead you could do...

For Rails 3.0:

Linkedpub.where(:id => @associated_linked_pub)

For Rails 2.x:

LinkedPub.find(:all, :conditions => { :id => @associated_linked_pub })

Rails will automatically create a SQL IN query such as:

SELECT * FROM linkedpubs WHERE id IN (34, 6, 2, 67, 8)
Jits
  • 9,647
  • 1
  • 34
  • 27
3
linkedpub.LPU_ID.in?(@associated_linked_pub.collect(&:id))

Using in? in these cases has always felt more natural to me.

bigtex777
  • 1,150
  • 10
  • 15
1
@associated_linked_pub.collect(&:id).include?(linkedpub.LPU_ID)
Ken Bloom
  • 57,498
  • 14
  • 111
  • 168
Sameer C
  • 2,777
  • 1
  • 18
  • 12
1

if @associated_linked_pub is an array, try

if @associated_linked_pub.include?(linkedpub.LPU_ID)
John Bachir
  • 22,495
  • 29
  • 154
  • 227