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:
- all?
- any?
- collect / map
- count
- cycle
- detect / find
- drop
- drop_while
- each_cons
- each_slice
- each_with_index
- entries / to_a
- find_all / select
- find_index
- first
- grep
- group_by
Enumerable#include? Quick Summary
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 |
|
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
# Here's a list of words (if they seem unfamiliar, go read # http://en.wikipedia.org/wiki/Zoom_schwartz_profigliano) 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?”
Examples
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?”
[…] have all of Ruby’s functional niceties), but I have no excuse for blowing this. I’ve actually written a whole series of articles on the power of Ruby’s Enumerable module, including the […]