Why is_a? returns false for Hash class? Why is_a? returns false for Hash class? ruby ruby

Why is_a? returns false for Hash class?


#irbruby-1.9.3-p0 :001 > value = {"x" => 3, "y" => 2} => {"x"=>3, "y"=>2} ruby-1.9.3-p0 :002 > value.is_a?(Hash) => true

try to disable any gems/extensions you have loaded, and try with clean ruby

UPDATE:

try value.is_a?(::Hash)

PS: try to read about Duck Typing in Ruby. Maybe you should call value.respond_to?(:key) instead of value.is_a?(Hash)


When I added "::" before Hash class it starts working.

puts value.classputs value.is_a?(::Hash)

Output:

Hashtrue


It doesn't.

dave@hpubuntu1:~ $ rvm listrvm rubies   ruby-1.8.7-p334 [ i386 ]   jruby-1.6.2 [ linux-i386-java ]   ruby-1.9.2-p0 [ i386 ]   ruby-1.9.2-p290 [ i386 ]   ruby-1.9.3-p0 [ i386 ]=> ruby-1.9.2-p180 [ i386 ]dave@hpubuntu1:~ $ prypry(main)> value = {"x" => 3, "y" => 2}=> {"x"=>3, "y"=>2}pry(main)> value.is_a? Hash=> true

A Mongoid Hash isn't a pure-Ruby Hash, nor does it extend it. You should check the actual type, probably by using type.

Just because something prints out Hash doesn't mean (a) that it's part of the inheritance chain you think it is, and (b) that it's a Hash (witness ActiveRecord Array, which lies, to a degree).