Check if Value Exists in Array in Ruby

  1. Use the Array#include? Method to Check if Value Exists in Ruby Array
  2. Use the Array#any? Method to Check if Value Exists in Ruby Array
  3. Use the Array#index Method to Check if Value Exists in Ruby Array

In Ruby, an array is a common data type. It contains elements of various data types, including number, string, boolean, and even another array.

We may need to check if a value exists in a given array in some circumstances. This article shows how to do so using the array’s built-in methods.

Use the Array#include? Method to Check if Value Exists in Ruby Array

Array#include? seems to be the most straightforward way to check if a value resides within an array.

If an element is in the array, Array#include? returns true, otherwise false.

print(['ruby', 'sapphire', 'amber'].include?('ruby'))
print("\n")
print(['ruby', 'sapphire', 'amber'].include?('moonstone'))

Output:

true
false

Use the Array#any? Method to Check if Value Exists in Ruby Array

We could also use Array#any? instead of Array#include? to see if an array contains a value. Because Array#any? accepts a block, it’s ideal for complex checking logic.

It returns true if the block returns a value other than false or nil.

print(['ruby', 'sapphire', 'amber'].any? { |gem| gem == 'moonstone' })
print("\n")
print(['ruby', 'sapphire', 'amber'].any? { |gem| gem == 'ruby' })

Output:

false
true

The code below will use any? to see if the array contains any gems with a size greater than four.

print(['ruby', 'sapphire', 'amber'].any? { |gem| gem.size > 4 })

Output:

true

Use the Array#index Method to Check if Value Exists in Ruby Array

It either takes a single value, as include? does, or a block.

Array#index return index of the matched value, otherwise returns nil, unlike include? and any? which return boolean.

print(['ruby', 'sapphire', 'amber'].index { |gem| gem == 'ruby' })
print("\n")
print(['ruby', 'sapphire', 'amber'].index { |gem| gem.size > 10 })

Output:

0
#returns nil
Write for us
DelftStack articles are written by software geeks like you. If you also would like to contribute to DelftStack by writing paid articles, you can check the write for us page.

Related Article - Ruby Array

  • Map an Array With Index in Ruby
  • Find a Value in a Ruby Array