Enumerating Enumerable: Enumerable#include?

by Joey deVilla on September 2, 2008

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 Ruby-Doc.org’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.
Returns
  • 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.
RubyDoc.org’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.

Examples

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?”

Examples

Previous post:

Next post: