Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't all or most cases of `each` be replaced with `map`?

Tags:

each

ruby

map

The difference between Enumerable#each and Enumerable#map is whether it returns the receiver or the mapped result. Getting back to the receiver is trivial and you usually do not need to continue a method chain after each like each{...}.another_method (I probably have not seen such case. Even if you want to get back to the receiver, you can do that with tap). So I think all or most cases where Enumerable#each is used can be replaced by Enumerable#map. Am I wrong? If I am right, what is the purpose of each? Is map slower than each?

Edit: I know that there is a common practice to use each when you are not interested in the return value. I am not interested in whether such practice exists, but am interested in whether such practice makes sense other than from the point of view of convention.

like image 949
sawa Avatar asked Sep 30 '12 07:09

sawa


People also ask

What does map () do in Python?

Python's map() is a built-in function that allows you to process and transform all the items in an iterable without using an explicit for loop, a technique commonly known as mapping. map() is useful when you need to apply a transformation function to each item in an iterable and transform them into a new iterable.

What does map () return in Python?

map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable (list, tuple etc.)

Can map take multiple arguments?

You can pass as many iterable as you like to map() function in Python.

How many arguments does map take?

The map function takes two arguments: an iterable and a function , and applies the function to each element of the iterable. The return value is a map object ;).


2 Answers

The difference between map and each is more important than whether one returns a new array and the other doesn't. The important difference is in how they communicate your intent.

When you use each, your code says "I'm doing something for each element." When you use map, your code says "I'm creating a new array by transforming each element."

So while you could use map in place of each, performance notwithstanding, the code would now be lying about its intent to anyone reading it.

like image 199
Wayne Conrad Avatar answered Oct 18 '22 18:10

Wayne Conrad


The choice between map or each should be decided by the desired end result: a new array or no new array. The result of map can be huge and/or silly:

p ("aaaa".."zzzz").map{|word| puts word} #huge and useless array of nil's
like image 5
steenslag Avatar answered Oct 18 '22 20:10

steenslag