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
First of all, the best answer for the literal question is
Hash === @some_var
But the question really should have been answered by showing how to do duck-typing here. That depends a bit on what kind of duck you need.
@some_var.respond_to?(:each_pair)
or
@some_var.respond_to?(:has_key?)
or even
@some_var.respond_to?(:to_hash)
may be right depending on the application.
Usually in ruby when you are looking for "type" you are actually wanting the "duck-type" or "does is quack like a duck?". You would see if it responds to a certain method:
@some_var.respond_to?(:each)
You can iterate over @some_var because it responds to :each
If you really want to know the type and if it is Hash or Array then you can do:
["Hash", "Array"].include?(@some_var.class) #=> check both through instance class
@some_var.kind_of?(Hash) #=> to check each at once
@some_var.is_a?(Array) #=> same as kind_of
irb(main):005:0> {}.class
=> Hash
irb(main):006:0> [].class
=> Array