How to Check If a Value Exists in an Array in Ruby

How to check if a value exists in an array in Ruby

You're looking for include?:

>> ['Cat', 'Dog', 'Bird'].include? 'Dog'
=> true

How can i check if a value exists in an array?

You could use any?:

checkresults.any? { |r| !r.status }

This will return a true or false for you.

How to check if a specific value exists in a multidimensional array?

If you know you only have an array-of-arrays (i.e. exactly two levels) then you could use Array#any? and Array#include?:

array.any? { |a| a.include?(word) }

Both any? and include? short circuit so they'll return true as soon as the target is found.

How to check if a specific value exists between values in an array in Ruby

let's check if any of the array's items include Soap

soap_present = arr.any? { |item| item.include?('Soap') }

How to check if a key exists in an array of arrays?

If you only need a true/false answer you can flatten the array and call include on that:

>> myArray.flatten.include?("c")
=> true

Determine if a value exists in an array of hashes

array_of_hashes.any? {|h| h[:a] == 11}

Check if certain value exists in array of hash map

The any? and include? methods sound like what you need.


params.any? { |param| param.include?(:sku) }

This is an efficient way to do it, as it "short circuits", stopping as soon as a match is found.

How would I check if a value is found in an array of values

You can use Array#include?


if @associated_linked_pub.include? linkedpub.LPU_ID


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

if{|a|}.include? linkedpub.LPU_ID


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)

Related Topics

Leave a reply