Enumerating Enumerable: Enumerable#entries / Enumerable#to_a

by Joey deVilla on August 2, 2008

Enumerating Enumerable

We’re at the dirty dozen now — this is the twelfth entry in Enumerating Enumerable, my series of articles on the methods in that Ruby workhorse, the Enumerable module. In this article, I cover the entries method, also known as the to_a method. I myself prefer to_a to entries, as its meaning is more obvious.

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

Enumerable#entries / Enumerable#to_a Quick Summary

In the simplest possible terms Turns any collection into an array.
Ruby version 1.8 and 1.9
Expects Nothing.
Returns An array containing the collection's items.
RubyDoc.org's entry Enumerable#entries / Enumerable#to_a

Enumerable#entries / Enumerable#to_a and Arrays

Converting arrays into arrays isn't terribly useful, but it is possible. Note that the array returned is the same object as the original array!

Enumerable#entries / Enumerable#to_a and Ranges

entries / to_a converts ranges into ascending-order arrays:

Enumerable#entries / Enumerable#to_a and Hashes

When used on a hash, entries / to_a creates an array made up of the items in the hash, converting each hash item into a two-element array, where the first element is the key and the second element is the corresponding value.

Leave a Comment

Previous post:

Next post: