Project

General

Profile

Feature #10254

Array#each and Array#map for nested arrays

Added by sawa (Tsuyoshi Sawada) almost 5 years ago. Updated almost 5 years ago.

Status:
Feedback
Priority:
Normal
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]

History

Updated by matz (Yukihiro Matsumoto) almost 5 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) almost 5 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) almost 5 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.

Also available in: Atom PDF