include? and member? Methods

The include? and member? methods do the same thing: test whether a given item is in the enumerable collection. For the rest of this article, we'll use the include? method to avoid confusion, but member? works just as well.

Number List

@numbers = [1, 0, 3, 2, 5, 4, 7, 6, 9, 8]

# does list include the number five?
@numbers.include?(5)    #=> true

# does list include the number 100?
@numbers.include?(100)    #=> false

Unlike a lot of other Enumerable methods, include? doesn't accept a block. It accepts a single object, and checks for that object in the collection.

Pet Inventory

# does inventory include dogs?
dog = @inventory.first
@inventory.include?(dog)    #=> true

# does inventory include zebras?
zebra ='zebra', 4, 0)
@inventory.include?(zebra)    #=> false

# does a different object with the same attributes count?
similar_dog ='dog', 4, 100)
@inventory.include?(similar_dog)    #=> false

One thing of note in this example is that two objects of the same class, that contain all the same info, are not considered the same item. Even though the pet inventory contains a "dog" category with 4 legs and 100 in stock, our similar_dog item doesn't count as being included in the inventory.

One notable exception is very simple objects, like numbers or arrays. A good rule of thumb is this: if you have to call new to create the object, it's not going to be "the same enough" for the include? method.

Pokey Things

# is cactus on the list of pokey things?'cactus')    #=> true

# are pillows on the list of pokey things?'pillow')    #=> false

If you're using Enumerable methods on a filehandle, remember two things. First, you have to reset the file position before each call to an Enumerable method. Second, every item in the collection is a line in the file, complete with newline character(s) at the end. Chances are, you'll want to chomp them as in the examples above.

Heroku Log File

# any heroku requests result in error?'error')    #=> true

# any missing page errors?    #=> false

Leave a Reply

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