Read more

Alternative to #to_a and Array(...)

Henning Koch
June 06, 2011Software engineer at makandra GmbH

Note: In Rails 3+ you can use Array.wrap Show archive.org snapshot instead of the solution here.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

In the past you could use Array(...) or #to_a to turn an object into an array, unless it already is an array:

Array(5) # => [5]
Array([5]) # => [5]

Unfortunately this idiom has issues and it also triggers deprecation warnings like this one:

warning: default `to_a' will be obsolete

For an alternative you can copy the attached file to config/initializers or require it from a non-Rails project. You can now say:

5.listify # => [5]
[5].listify # => [5]

Note that this method no longer treats nil receivers as a special case:

Array(nil) # => []
nil.listify # => [nil]
Posted by Henning Koch to makandra dev (2011-06-06 14:32)