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 statement
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')
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 =
puts categories.?(selected)
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)
.?(format)
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.
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 |
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
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 ?
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
How to Call Shell Commands from Ruby and Capture Output
Learn how to run shell commands in Ruby, capture output, check exit status, and choose the right method for scripts and apps.
How to Check Whether a String Contains a Substring in Ruby
Learn how to check if a string contains a substring in Ruby using include?, match, and multiline string examples.
How to Check if a Hash Key Exists in Ruby
Learn how to check whether a specific key exists in a Ruby hash using key?, has_key?, and include? with clear examples.