What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

drhyde picture drhyde · Mar 20, 2011 · Viewed 108.3k times · Source

To check what @some_var is, I am doing a

if @some_var.class.to_s == 'Hash' 

I am sure there is a more elegant way to check if @some_var is a Hash or an Array.

Answer

Pete picture Pete · Mar 20, 2011

You can just do:

@some_var.class == Hash

or also something like:

@some_var.is_a?(Hash)

It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:

@some_var.is_a?(Object)  # => true

the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.