Enumerating Enumerable: Enumerable#include?

Enumerating Enumerable

Welcome to the eighteenth installment of Enumerating Enumerable!

In this series of articles, I’m going through the methods in Ruby’s Enumerable in alphabetical order, explaining what each does and providing examples. This is my attempt to make better documentation for Ruby’s Enumerable module than’s.

In this article, I cover the include? method.

In case you missed any of the previous articles, they’re listed and linked below:

  1. all?
  2. any?
  3. collect / map
  4. count
  5. cycle
  6. detect / find
  7. drop
  8. drop_while
  9. each_cons
  10. each_slice
  11. each_with_index
  12. entries / to_a
  13. find_all / select
  14. find_index
  15. first
  16. grep
  17. group_by

Enumerable#include? Quick Summary

Graphic representation of the "include?" method in Ruby's "Enumerable" module.

In the simplest possible terms Does the collection contain an item equal to this one?
Ruby version 1.8 and 1.9
Expects An argument containing the item to search for in the collection.
  • true if there is at least one item in the collection that is equal (using the == operator) to the argument.
  • false if no item in the collection is equal (using the == operator) to the argument.’s entry Enumerable#include?

Enumerable#include? and Arrays

When used on an array, include? iterates through it, comparing items in the array with the argument using the == operator. If any of these comparisons has a result of true, include? returns true. If you think of arrays as sets, you can think of include? as a set membership test.


# Here's a list of words (if they seem unfamiliar, go read
words = ["zoom", "schwartz", "profigliano", "butterman"]
=> ["zoom", "schwartz", "profigliano", "butterman"]

# Is "profigliano" in our list of words?
words.include? "profigliano"
=> true

# How about "kwyjibo"?
words.include? "kwyjibo"
=> false

Enumerable#include? and Hashes

include?, when used with a hash, behaves differently than you might expect. You might think that include? would return true if given a two-element array argument that matched an item in the hash, where the first element matched the key and the second element matched the corresponding value.

However, that is not the case. Instead, include? returns true if there is a key in the hash that is equivalent to the given argument when compared with the == operator. In other words, include?, when used with a hash, answers the question “Is there an item in this hash with this key?”


values = {"zoom" => 1, "schwartz" => 5, "profigliano" => 10, "butterman" => 25}
=> {"zoom"=>1, "schwartz"=>5, "profigliano"=>10, "butterman"=>25}

values.include? "schwartz"
=> true

values.include? ["schwartz", 5]
=> false

values.include? "kwyjibo"
=> false

One reply on “Enumerating Enumerable: Enumerable#include?”

Leave a Reply

Your email address will not be published. Required fields are marked *