Categories
Uncategorized

Enumerating Enumerable: Enumerable#entries / Enumerable#to_a

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!

names = ["alice", "bob", "carol"]
=> ["alice", "bob", "carol"]

new_names = names.to_a
=> ["alice", "bob", "carol"]

# Let's make a change to new_names
new_names[1] = "billy"
=> "billy"

new_names
=> ["alice", "billy", "carol"]

# entries / to_a, when used on an array returns the same object
# as the original array -- names and new_names are the same array!
names
=> ["alice", "billy", "carol"]

Enumerable#entries / Enumerable#to_a and Ranges

entries / to_a converts ranges into ascending-order arrays:

(1..10).to_a
=> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

 ("aa".."az").to_a
=> ["aa", "ab", "ac", "ad", "ae", "af", "ag", "ah", "ai", "aj", "ak", "al",
"am", "an", "ao", "ap", "aq", "ar", "as", "at", "au", "av", "aw", "ax", "ay", "az"]

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.

names = {:sender => "Alice", :receiver => "Bob", :man_in_the_middle => "Carol"}
=> {:sender=>"Alice", :receiver=>"Bob", :man_in_the_middle=>"Carol"}

names.to_a
=> [[:sender, "Alice"], [:receiver, "Bob"], [:man_in_the_middle, "Carol"]]