liveBook · Manning

Array method

As explained in The Well-Grounded Rubyist, Fourth Edition

The Array method is a Ruby top-level conversion method that returns an array representation of its argument.

Array is a top-level Ruby conversion method that returns an array representation of its argument. For an ordinary string, it wraps the string as one element. section 9.2.1

Converting a string

Array("A string") returns ["A string"]. If the string is given a to_a method that splits it into characters, Array(string) instead returns ["A", " ", "s", "t", "r", "i", "n", "g"]. section 9.2.1

>> string = "A string"
=> "A string"
>> string.respond_to?(:to_ary)
=> false
>> string.respond_to?(:to_a)
=> false
>> Array(string)      1
=> ["A string"]
>> def string.to_a       2
>>   split(//)
>> end
=> nil
>> Array(string)
=> ["A", " ", "s", "t", "r", "i", "n", "g"]

Compare the default conversion with conversion after defining to_a on the string. section 9.2.1

Array belongs alongside Array.new, literal arrays, and %w or %i notation as one of Ruby’s ways to create arrays, but its distinctive role is converting an existing argument. section 9.2.1

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains ordinary wrapping and object-defined to_a behavior, while stopping short of a complete conversion protocol reference.
Examples
Uses string conversion, a dynamically defined to_a method, and Array.try_convert with an object-defined to_ary method.
What you can do after
Apply it to obtain an array from an argument and observe how conversion methods affect the result.
How it connects
Connects Array with Array.new, array literals, to_a, to_ary, and Array.try_convert.

Also explained in

Compare how 2 books explain array method →

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.