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:
- all?
- any?
- collect / map
- count
- cycle
- detect / find
- drop
- drop_while
- each_cons
- each_slice
- 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"]]