Does `map` use everyone or not?

In Ruby, the Enumerable module mixes with collection classes and relies on a class serving each method, which gives each item in the collection.

Ok, so if I want to use Enumerable in my class, I just implement each [1]:

 class Colors include Enumerable def each yield "red" yield "green" yield "blue" end end > c = Colors.new > c.map { |i| i.reverse } #=> ["der", "neerg", "eulb"] 

This works as expected.

But if I override each method in an existing class with Enumerable, it does not break functions like map . Why not?

 class Array def each puts "Nothing here" end end > [1,2,3].each {|num| puts num } #=> "Nothing here" > [1,2,3].map {|num| num**2 } #=> [1,4,9] 

[1]: from http://www.sitepoint.com/guide-ruby-collections-iii-enumerable-enumerator/

+6
source share
1 answer

Enumerable map implementation does use each , but nothing stops the class extension from overriding it with its own implementation, which does not use each .

In this case, Array provides its own map implementation for performance reasons.

+7
source

Source: https://habr.com/ru/post/974275/


All Articles