Editing Topic: RCR244 Project: RCR | RCRchive home

RCR 244: Limit recursion depth of Array#flatten

submitted by matthias_georgi on Tue Apr 13 2004 04:19:08 AM -0700

Status: pending


Abstract

Let Array#flatten and Array#flatten! take an argument, which limits the recursion depth of flattening.

Problem

If you want
[ [:a, 1], [:b, [2, 3]] ] to result in
[ :a, 1, :b, [2, 3] ]
, Array#flatten is not appropiate.

This is useful for making Hashs like:

module Enumerable
  def make_hash(&block)
    Hash[* map(&block).flatten(1) ]
  end
end
This way one can return a tuple in each iteration as [key, value] pair.

Proposal

Array#flatten takes one integer argument and stops the recursion if desired depth is reached. The default is set to -1, which means no limit. A value of 1 only flattens the first level and leaves deeper levels untouched.

Analysis

This Change doesn't break existing code and would allow much faster Hash creation in combination with something like make_hash. It is useful in all cases, when someone wants to expand an Array as result of a block with nested Arrays preserved.

Implementation

Implementation is easy.
In array.c flatten(), rb_ary_flatten_bang(), rb_ary_flatten() need one additional limit argument.
flatten() returns if limit is 0 or decrease limit by one.


Back to RCRchive.


RCR Submission page and RCRchive powered by Ruby, Apache, RuWiki (modified), and RubLog