Ruby - test for array
Are you sure it needs to be an array? You may be able to use respond_to?(method)
so your code would work for similar things that aren't necessarily arrays (maybe some other enumberable thing). If you do actually need an array
, then the post describing the Array#kind\_of?
method is best.
['hello'].respond_to?('each')
Instead of testing for an Array,
just convert whatever you get into a one-level Array,
so your code only needs to handle the one case.
t = [*something] # or...t = Array(something) # or...def f *x ...end
Ruby has various ways to harmonize an API which can take an object or an Array of objects, so, taking a guess at why you want to know if something is an Array, I have a suggestion.
The splat operator contains lots of magic you can look up, or you can just call Array(something)
which will add an Array wrapper if needed. It's similar to [*something]
in this one case.
def f x p Array(x).inspect p [*x].inspectendf 1 # => "[1]"f [1] # => "[1]"f [1,2] # => "[1, 2]"
Or, you could use the splat in the parameter declaration and then .flatten
, giving you a different sort of collector. (For that matter, you could call .flatten
above, too.)
def f *x p x.flatten.inspectend # => nilf 1 # => "[1]"f 1,2 # => "[1, 2]"f [1] # => "[1]"f [1,2] # => "[1, 2]"f [1,2],3,4 # => "[1, 2, 3, 4]"
And, thanks gregschlom, it's sometimes faster to just use Array(x)
because when it's already an Array
it doesn't need to create a new object.