liveBook · Manning

To_a

As explained in The Well-Grounded Rubyist, Fourth Edition

to_a is a Ruby conversion method that produces an array representation of an object.

to_a produces an array-like representation of an object. It belongs to Ruby’s to_* conversion family, alongside to_s, to_sym, to_i, and to_f, but fewer objects define it than to_s. section 7.4.2 section 7.4

Common objects and uses include:

  • Convert a Range such as (1..5) into [1, 2, 3, 4, 5]. section 7.4.2
  • Convert Enumerable objects, including Hash, Range, Struct, and Enumerator, into arrays for iteration or further processing. section 7.4.2
  • Use a Struct’s to_a result as an array of attribute values, such as laptop operating systems and manufacturers. section 7.4.2
  • Let Array(obj) prefer to_ary, fall back to to_a, and otherwise wrap obj as a one-element array. section 9.2.1

Conversion and splatting

Given array = [1, 2, 3, 4, 5], [*array] produces [1, 2, 3, 4, 5], while [array] produces [[1, 2, 3, 4, 5]]. The splat operator unwraps an array—or an object responding to to_a—into a bare list. The same technique passes names = ["David", "Black"] as separate arguments to combine_names(*names). section 7.4.2

(1..5).to_a
=> [1, 2, 3, 4, 5]

A minimal Range conversion shows the ordinary shape of a to_a result. section 7.4.2

Computer = Struct.new(:os, :manufacturer)     1
laptop1 = Computer.new("linux", "Lenovo")
laptop2 = Computer.new("os x", "Apple")
[laptop1, laptop2].map { |laptop| laptop.to_a }      2
=> [["linux", "Lenovo"], ["os x", "Apple"]]

A Struct conversion demonstrates collecting each object’s attribute values into nested arrays. section 7.4.2

>> array = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
>> [*array]
=> [1, 2, 3, 4, 5]

Compare direct array splatting with the nested result of wrapping the same array without splatting. section 7.4.2

def combine_names(first_name, last_name)
  first_name + " " + last_name
end
names = ["David", "Black"]
puts combine_names(*names)       #1

A method-call example shows splatting an array into separate positional arguments. section 7.4.2

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains array representations, Enumerable support, Array conversion precedence, and splat behavior through runnable examples.
Examples
Uses Range conversion, Struct attribute arrays, Array(string), nested splatting, and splatted method arguments.
What it assumes
Assumes Ruby objects and arrays; teaches conversion methods, Enumerable relationships, and splat behavior through examples.
What you can do after
Apply it via Ruby’s Array conversion and splat syntax when an object supplies an array representation.
How it connects
Connects to Enumerable, Array, Range, Struct, Enumerator, to_ary, and the splat operator.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.