Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 22 / 68

Searching an Array (include?)

In this lesson you will learn to search an array with Ruby's include? method so you can check efficiently whether a value is present. This is for anyone searching for "Ruby include? how to use".

.include?(value) reports true or false depending on whether the array contains that value. The trailing ? in the method name is characteristically Ruby - a widely used convention for methods that return a boolean.

The sample code checks membership with fruits.include?("orange") and fruits.include?("banana"). Compare the true result when the value is present with the false when it is not.

A common stumbling block for beginners is simply getting used to method names with a ?. A question-form name such as include? signals that it returns a boolean, and once you know the convention you can guess what an unfamiliar method does.

Beyond arrays, strings and hashes and many other classes also provide include? - part of Ruby's consistent design. any? and all? are similar in spirit and used depending on the condition.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)