I need to convert a passed in argument (single object or collection) to an Array. I don't know what the argument is. If it is an Array already, I want to leave it, otherwise create a one-element array from it. I'm looking to allow both method(:objs => obj)
and method(:objs => [obj1, obj2])
This seems to be the best way (Array#to_a returns self):
arg = arg.to_a
But the ruby docs say Object#to_a
will soon be obsolete. Is there convenient replacement?
Anything more succinct than this?
arg = arg.respond_to?(:to_a) ? arg.to_a : [arg]
Use the method Kernel#Array:
Array([1,2,3]) #=> [1, 2, 3] Array(123) #=> [123]
Yes it may look like a class at first but this is actually a method that starts with a capital letter.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With