1. Technology
You can opt-out at any time. Please refer to our privacy policy for contact information.

Enumerable: Picking Out Just What You Want

By

The Enumerable mixin provides a collection interface to all manner of collections in Ruby. A collection is just what it sounds like, any object that holds a collection of other objects. Common collections in Ruby are the Array and Hash, but anything that holds objects and implements the each method to iterate over them can use the Enumerable mixin. Of the most commonly used methods in Enumerable are the ones that allow you to select, copy, remove or sort elements based on a simple criteria.

Find All Elements That Match

Imagine you have an array of numbers and strings, such as [1, "two", 3, 4, "five"] and you want to pull out a list of just the numbers. The method select or find_all (they're aliases for the same method) will do this for you. It takes a single block parameter, to which every element of the collection will be passed. For every element that the block returns true for, it will copy this into a new Array and returned from the select method.

As always, it's probably best explained in code.

#!/usr/bin/env ruby
require 'pp'

a = [1, "two", 3, 4, "five"]
pp a

b = a.select{|o| o.is_a?(Numeric) }
pp b

Note that select won't modify the original collection in any way. The methods that modify the collection will be marked with an exclamation point (as is the convention with Ruby methods).

  1. About.com
  2. Technology
  3. Ruby
  4. Beginning Ruby
  5. Collections: Arrays, Hashes and Enumerable
  6. Enumerable: Picking Out Just What You Want

©2014 About.com. All rights reserved.