Project

General

Profile

Actions

Feature #5663

closed

Combined map/select method

Added by wycats (Yehuda Katz) over 12 years ago. Updated almost 4 years ago.

Status:
Closed
Target version:
-
[ruby-core:41213]

Description

It is pretty common to want to map over an Enumerable, but only include the elements that match a particular filter. A common idiom is:

enum.map { |i| i + 1 if i.even? }.compact

It is of course also possible to do this with two calls:

enum.select { |i| i.even? }.map { |i| i + 1 }

Both cases are clumsy and require two iterations through the loop. I'd like to propose a combined method:

enum.map_select { |i| i + 1 if i.even? }

The only caveat is that it would be impossible to intentionally return nil here; suggestions welcome. The naming is also a strawman; feel free to propose something better.


Related issues 2 (0 open2 closed)

Related to Ruby master - Feature #13784: Add Enumerable#filter as an alias of Enumerable#selectClosedEregon (Benoit Daloze)Actions
Related to Ruby master - Feature #15323: [PATCH] Proposal: Add Enumerable#filter_mapClosedActions
Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0