Question
I have a value, 'Dog', and an array:
animals = ['Cat', 'Dog', 'Bird']
How can I check whether 'Dog' exists in the array in Ruby?
I want a simple way to test whether the value is present, without manually writing a loop or doing anything beyond checking for existence.
Short Answer
By the end of this page, you will understand how to check whether a value exists in a Ruby array using built-in methods like include?. You will also learn how Ruby performs this check internally, when to use related methods, and what mistakes beginners commonly make.
Concept
In Ruby, arrays come with built-in methods for searching and membership checks. The most direct way to test whether a specific value is present in an array is the include? method.
animals = ['Cat', 'Dog', 'Bird']
animals.include?('Dog')
# => true
This matters because checking whether a value exists is a very common task in programming:
- validating user input
- checking permissions
- matching tags or categories
- deciding whether to run some logic
Even though you do not write a loop yourself, Ruby still checks the array elements behind the scenes. The advantage is that you use a clear, readable method instead of manually iterating.
For arrays, include? checks whether any element is equal to the given value. In most cases, this is the simplest and most idiomatic Ruby solution.
Mental Model
Think of an array like a row of labeled boxes:
- box 1:
Cat - box 2:
Dog - box 3:
Bird
When you ask Ruby:
animals.include?('Dog')
you are basically saying:
“Is there any box in this row that contains exactly
'Dog'?”
Ruby looks through the row for you and answers with either:
trueif it finds itfalseif it does not
So include? is like asking a yes-or-no question about the contents of the array.
Syntax and Examples
Basic syntax
array.include?(value)
arrayis the array you want to searchvalueis the item you are looking for- the result is
trueorfalse
Example 1: Check for a string
animals = ['Cat', 'Dog', 'Bird']
puts animals.include?('Dog')
# true
puts animals.include?('Fish')
# false
This checks whether each string appears in the array.
Example 2: Check for a number
numbers = [10, 20, 30]
puts numbers.include?(20)
# true
puts numbers.include?(99)
# false
include? works with numbers as well.
Example 3: Use in an if statement
animals = ['Cat', 'Dog', 'Bird']
if animals.include?('Dog')
puts 'Dog is in the array'
else
puts 'Dog is not in the array'
end
This is how membership checks are commonly used in real programs.
Step by Step Execution
Consider this code:
animals = ['Cat', 'Dog', 'Bird']
result = animals.include?('Dog')
puts result
Step by step:
- Ruby creates an array and stores it in
animals:['Cat', 'Dog', 'Bird'] - Ruby runs:
animals.include?('Dog') - Ruby checks the array elements until it finds a match.
- Since
'Dog'is present, the expression returnstrue. - That
truevalue is stored inresult. puts resultprints:true
If the code were:
result = animals.include?('Fish')
then Ruby would not find a match, so result would be false.
Real World Use Cases
Checking whether a value exists in an array appears in many everyday Ruby programs.
User role checks
roles = ['admin', 'editor', 'viewer']
if roles.include?('admin')
puts 'Show admin dashboard'
end
Input validation
allowed_statuses = ['pending', 'approved', 'rejected']
status = 'approved'
unless allowed_statuses.include?(status)
puts 'Invalid status'
end
Feature flags
enabled_features = ['chat', 'notifications', 'search']
if enabled_features.include?('search')
puts 'Enable search UI'
end
Filtering by category
categories = ['books', 'music', 'games']
selected = 'music'
puts 'Valid category' if categories.include?(selected)
In all of these examples, the goal is the same: answer a simple yes-or-no question about membership.
Real Codebase Usage
In real Ruby codebases, include? is often used as part of small, readable checks.
Guard clauses
def process_status(status)
allowed_statuses = ['pending', 'approved', 'rejected']
return 'Invalid status' unless allowed_statuses.include?(status)
"Processing #{status}"
end
This pattern exits early if the value is not allowed.
Validation logic
def valid_role?(role)
['admin', 'editor', 'viewer'].include?(role)
end
This keeps validation simple and reusable.
Configuration checks
SUPPORTED_FORMATS = ['json', 'xml', 'csv']
def export(format)
raise 'Unsupported format' unless SUPPORTED_FORMATS.include?(format)
"Exporting as #{format}"
end
Conditional behavior
premium_features = ['analytics', 'priority_support']
def feature_available?(feature, available_features)
available_features.include?(feature)
end
Developers often combine include? with:
returnfor early exits- validation methods ending in
? - constants that store allowed values
- conditionals like
if,unless, and ternary expressions
Common Mistakes
1. Using the wrong capitalization
Strings in Ruby are case-sensitive.
animals = ['Cat', 'Dog', 'Bird']
puts animals.include?('dog')
# false
'dog' is not the same as 'Dog'.
To avoid this, normalize values if needed:
animals.map(&:downcase).include?('dog')
# true
2. Comparing strings and symbols
Strings and symbols are different types.
animals = ['Cat', 'Dog', 'Bird']
puts animals.include?(:Dog)
# false
If your array contains strings, search with strings.
3. Expecting include? to return the item itself
include? returns only true or false.
animals = ['Cat', 'Dog', 'Bird']
value = animals.include?('Dog')
puts value
# true
If you need the actual matching item, use find instead.
4. Thinking there is no loop involved at all
You do not write the loop, but Ruby still checks elements internally. include? is a cleaner way to express the intent.
5. Calling include? on nil
animals = nil
animals.include?('Dog')
# NoMethodError
Make sure the object is actually an array:
animals&.include?('Dog')
# nil
or provide a default:
Array(animals).include?('Dog')
# false
Comparisons
include? vs related methods
| Method | What it returns | Best use case |
|---|---|---|
include?(value) | true or false | Check whether a value exists |
find { ... } | Matching element or nil | Get the first matching element |
any? { ... } | true or false | Check whether any element matches a condition |
index(value) | Index number or nil | Find the position of a value |
Example comparison
animals = ['Cat', 'Dog', 'Bird']
animals.include?('Dog') # => true
animals.find { |a| a == 'Dog' } # => "Dog"
animals.any? { |a| a.start_with?('D') } # => true
animals.index('Dog') # => 1
When to choose which
- Use
include?when you only need yes or no. - Use
findwhen you need the actual element. - Use
any?when the condition is more complex than exact equality. - Use
indexwhen you need the element's position.
Cheat Sheet
Quick syntax
array.include?(value)
Returns
trueif the value existsfalseif the value does not exist
Example
animals = ['Cat', 'Dog', 'Bird']
animals.include?('Dog') # => true
animals.include?('Fish') # => false
Common patterns
if animals.include?('Dog')
puts 'Found it'
end
unless animals.include?('Fish')
puts 'Not found'
end
Important rules
- Matching is case-sensitive
- Strings and symbols are different
include?returns a boolean, not the matching item- Ruby checks the array internally even if you do not write a loop
Related methods
array.find { |item| item == value }
array.any? { |item| condition }
array.index(value)
FAQ
How do I check if a string exists in an array in Ruby?
Use include?:
animals.include?('Dog')
It returns true or false.
Does include? loop through the array in Ruby?
Internally, yes. You do not write the loop yourself, but Ruby still checks elements behind the scenes.
Is include? case-sensitive in Ruby?
Yes. 'Dog' and 'dog' are different strings.
What is the difference between include? and any? in Ruby?
include? checks for an exact value. any? checks whether any element matches a condition.
Can I use include? with numbers and symbols?
Yes, as long as the value type matches the elements in the array.
What if I need the matching item instead of true or false?
Use find instead of include?.
What happens if the array is empty?
include? simply returns false.
Mini Project
Description
Build a small Ruby script that checks whether a user's favorite animal is in a list of allowed animals. This demonstrates how to use include? in a practical input-validation scenario.
Goal
Create a script that stores a list of animals, checks whether a chosen value exists, and prints a clear message based on the result.
Requirements
- Create an array of at least four animal names.
- Store one animal name in a separate variable.
- Use
include?to check whether the animal exists in the array. - Print one message if it exists and another if it does not.
Keep learning
Related questions
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.