How to Use the Ruby include? Method

Contents
In this article, you will learn how to use the Ruby include? method.
Using the include? method
The include? method in Ruby is used to check whether a given object is present in an array or a string. It returns a boolean value (true or false) indicating whether the object is found or not. Here’s how you can use the include? method in Ruby:
Using include? with an array
Suppose you have an array of integers as follows:
numbers = [1, 2, 3, 4, 5]
You can check if a particular number is present in this array using the include? method as follows:
numbers.include?(3) # Output: true
numbers.include?(6) # Output: false
In the first example, the method returns “true” because the number 3 is present in the array. In the second example, the method returns “false” because the number 6 is not present in the array.
Using include? with a string
Suppose you have a string as follows:
string = "Hello, world!"
You can check if a particular substring is present in this string using the include? method as follows:
string.include?("world") # Output: true
string.include?("ruby") # Output: false
In the first example, the method returns “true” because the substring “world” is present in the string. In the second example, the method returns “false” because the substring “ruby” is not present in the string.
Case sensitivity
By default, the include? method is case sensitive. This means that if you search for a substring in a string, it will only return “true” if the case of the characters matches exactly. For example:
string = "Hello, world!"
string.include?("hello") # Output: false
To perform a case-insensitive search, you can convert both the string and the substring to lowercase (or uppercase) before using the include? method. For example:
string = "Hello, world!"
string.downcase.include?("hello") # Output: true