Last Updated: February 25, 2016
·
1.029K
· 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

Array(12)
#=> [12]

Array("asdf")
#=> ["asdf"]

But be wary of ranges and time values

Array(Time.mktime(2013,4,5,6,7,8))
#=> [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

Array(1..3)
#=> [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.