Ruby - test for array Ruby - test for array ruby ruby

Ruby - test for array


You probably want to use kind_of().

>> s = "something"=> "something">> s.kind_of?(Array)=> false>> s = ["something", "else"]=> ["something", "else"]>> s.kind_of?(Array)=> true


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.