Search code examples
rubyenumerable

Does Hash override Enumerable#map()?


Given that map() is defined by Enumerable, how can Hash#map yield two variables to its block? Does Hash override Enumerable#map()?

Here's a little example, for fun:

ruby-1.9.2-p180 :001 > {"herp" => "derp"}.map{|k,v| k+v}
 => ["herpderp"] 

Solution

  • It doesn't override map

    Hash.new.method(:map).owner # => Enumerable
    

    It yields two variables which get collected into an array

    class Nums
      include Enumerable
    
      def each
        yield 1
        yield 1, 2
        yield 3, 4, 5
      end
    end
    
    Nums.new.to_a # => [1, [1, 2], [3, 4, 5]]