Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does `map` use `each` or not?

In Ruby, the Enumerable module mixes into collection classes and relies on the class serving up an each method which yields each item in the collection.

Okay, so if I want to use Enumerable in my own class, I'll 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"]

That works as expected.

But if I override the each method on an existing class with Enumerable, it doesn't 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/

like image 730
Erik Trautman Avatar asked Aug 24 '14 21:08

Erik Trautman


People also ask

Should I use map or forEach?

The main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn't return anything. You can use the forEach method to mutate the source array, but this isn't really the way it's meant to be used.

What is difference between map () and forEach ()?

The returning value The first difference between map() and forEach() is the returning value. The forEach() method returns undefined and map() returns a new array with the transformed elements. Even if they do the same job, the returning value remains different.

Is map more efficient than forEach?

When I modify the tests to actually do the same thing, map is faster than foreach. I would argue it is scientific when used for the case of "I need to do something to each array element, what should I use?" question.

How does map method work?

The map() method in JavaScript creates an array by calling a specific function on each element present in the parent array. It is a non-mutating method. Generally map() method is used to iterate over an array and calling function on every element of array.


1 Answers

Enumerable's implementation of map does use each, but there's nothing stopping an extending class from overriding it with its own implementation that does not use each.

In this case Array does provide its own implementation of map for efficiency reasons.

like image 175
sepp2k Avatar answered Oct 10 '22 05:10

sepp2k