Last Updated: February 25, 2016
· adzap

Take care when using Kernel#Array()

The Kernel#Array() method is helpful when you want to convert or wrap an object in an array unless it is already an array, in which case it just returns itself.

However the way the method works is to try to call #to_ary and also #to_a. If the object responds one of these methods the result may not be what you expect.

For strings and numbers and many other core class instance objects this works fine

#=> [12]

#=> ["asdf"]

But be wary of ranges and time values

#=> [8, 7, 6, 5, 4, 2013, 5, 95, true, "EST"]

Which is the return value of #to_a on the time object.

Likewise with ranges

#=> [1,2,3]

It still pays to check the type if you need to wrap the object in an array if you expect times or ranges. But really any non-core class could respond to #to_ary or #to_a in a way you don't expect.