0

This works as expected:

h = { a: "alpha" }
h.kind_of?(Hash) # => true

However, when I try to extend a core Ruby class with a module, it doesn't seem to work:

module CoreExtensions
  module Hash
    module Keys
      def my_custom_method
        self.each do |k, v|
          self.kind_of?(Hash) # => false
        end
      end
    end
  end
end

Hash.include CoreExtensions::Hash::Keys

h = { a: "alpha" }
h.my_custom_method

Note that this is a contrived example of code that demonstrates my problem.

Is there something different about using object.kind_of?(Class) inside a module like this? My assumption is that using self is referencing the module somehow and not the actual Hash class, but self.class # => Hash so it "quacks" like a Hash class.

Dan L
  • 4,319
  • 5
  • 41
  • 74

1 Answers1

2

The Hash in self.kind_of?(Hash) refers to CoreExtensions::Hash. Try p Hash if you want to see for yourself.

Your code can be fixed by referring to the global Hash class instead: self.kind_of?(::Hash). See this question if you're not familiar with how :: is used here.

cremno
  • 4,672
  • 1
  • 16
  • 27
  • Ha! It's the little things that get you...I'm familiar with the :: but didn't even think about it here. Much appreciated. – Dan L Nov 05 '15 at 18:16