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
