Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Object.to_a replacement

Tags:

ruby

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] 
like image 499
Daniel Beardsley Avatar asked Dec 22 '08 10:12

Daniel Beardsley


1 Answers

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.

like image 63
Grant Hutchins Avatar answered Sep 23 '22 12:09

Grant Hutchins