Project

General

Profile

Actions

Feature #10254

closed

Array#each and Array#map for nested arrays

Added by sawa (Tsuyoshi Sawada) over 9 years ago. Updated over 9 years ago.

Status:
Feedback
Assignee:
-
Target version:
-
[ruby-core:65098]

Description

In order to allow iteration over elements of arrays nested within an array, I propose to pass Array#each and Array#map an optional argument that expresses the depth to iterate over.

Conventionally, iterating over nested elements requires nested each or map:

[[1, 2], [3, 4], [5, 6]].map{|a| a.map{|e| e + 1}} #=> [[2, 3], [4, 5], [6, 7]]
[[[1, 2], [3, 4]], [[5, 6]]].map{|a| a.map{|a| a.map{|e| e + 1}}} #=> [[[2, 3], [4, 5]], [[6, 7]]]

With the proposed optional argument, this would be done by:

[[1, 2], [3, 4], [5, 6]].map(1){|e| e + 1} #=> [[2, 3], [4, 5], [6, 7]]
[[[1, 2], [3, 4]], [[5, 6]]].map(2){|e| e + 1} #=> [[[2, 3], [4, 5]], [[6, 7]]]

Absence of the parameter should be understood as the parameter being defaulted to 0.

[1, 2, 3, 4, 5, 6].map{|e| e + 1} #=> [2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6].map(0){|e| e + 1} #=> [2, 3, 4, 5, 6, 7]

Updated by matz (Yukihiro Matsumoto) over 9 years ago

  • Status changed from Open to Feedback

It should be separated in different method, e.g. #nested_map in my opinion.

Matz.

Updated by avit (Andrew Vit) over 9 years ago

nested_map makes sense since there is a flat_map. This is similar but different:

[[[1, 2], [3, 4]], [[5, 6]]].flatten(2).map{|e| e + 1} #=> [2, 3, 4, 5, 6, 7]

Updated by trans (Thomas Sawyer) over 9 years ago

It's a shame it's not map_flat, and thus in this case map_nested, as it would organize documentation in a nicer fashion.

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0