Search code examples
rubyenumerable

Where is instance method "each_with_index" defined?


I am looking in Ruby 1.8.6 docs, and there is no mentioning of each_with_index there. But if I start up Ruby 1.8.7 or 1.9.2 and run the following, it works:

h = {:a => 1, :b => 2.2}
h.each_with_index do |pair, i|
  p pair, i
end

Where does each_with_index come from? Hash.superclasss is Object, and Object doesn't implement this instance method.


Solution

  • It comes from Enumerable, a module that's mixed in into Hash.

    Do Hash.ancestors to find mention of Enumerable.

    Hash.ancestors => [Hash, Enumerable, Object, Kernel, BasicObject]
    Enumerable.instance_methods.grep(/each/) # => [:each_with_index, :reverse_each, :each_slice, :each_cons, :each_with_object]