From 55bf7f9d40bae8671476b576a2c8e98bed27b1a6 Mon Sep 17 00:00:00 2001 From: matz Date: Sat, 24 Oct 2009 17:01:38 +0000 Subject: [PATCH] * enum.c (enum_flat_map): new method that concatenates the values from given block. also provides alias #collect_concat. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@25456 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ enum.c | 44 ++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/ChangeLog b/ChangeLog index a836c16396..da4dc17ccd 100644 --- a/ChangeLog +++ b/ChangeLog @@ -7,6 +7,11 @@ Sat Oct 24 13:38:45 2009 Yukihiro Matsumoto * object.c (rb_obj_cmp): defines Object#<=>. [ruby-core:24063] +Sat Oct 24 09:51:28 2009 Yukihiro Matsumoto + + * enum.c (enum_flat_map): new method that concatenates the values + from given block. also provides alias #collect_concat. + Sat Oct 24 00:36:47 2009 Tanaka Akira * io.c (io_cntl): update max file descriptor by the result of diff --git a/enum.c b/enum.c index 523e9bfe05..875beb9eaf 100644 --- a/enum.c +++ b/enum.c @@ -396,6 +396,48 @@ enum_collect(VALUE obj) return ary; } +static VALUE +flat_map_i(VALUE i, VALUE ary, int argc, VALUE *argv) +{ + VALUE tmp; + + i = enum_yield(argc, argv); + tmp = rb_check_array_type(i); + + if (NIL_P(tmp)) { + rb_ary_push(ary, i); + } + else { + rb_ary_concat(ary, tmp); + } + return Qnil; +} + +/* + * call-seq: + * enum.flat_map {| obj | block } => array + * enum.collect_concat {| obj | block } => array + * + * Returns a new array with the concatenated results of running + * block once for every element in enum. + * + * [[1,2],[3,4]].flat_map {|i| i } #=> [1, 2, 3, 4] + * + */ + +static VALUE +enum_flat_map(VALUE obj) +{ + VALUE ary; + + RETURN_ENUMERATOR(obj, 0, 0); + + ary = rb_ary_new(); + rb_block_call(obj, id_each, 0, 0, flat_map_i, ary); + + return ary; +} + /* * call-seq: * enum.to_a => array @@ -2375,6 +2417,8 @@ Init_Enumerable(void) rb_define_method(rb_mEnumerable, "reject", enum_reject, 0); rb_define_method(rb_mEnumerable, "collect", enum_collect, 0); rb_define_method(rb_mEnumerable, "map", enum_collect, 0); + rb_define_method(rb_mEnumerable, "flat_map", enum_flat_map, 0); + rb_define_method(rb_mEnumerable, "collect_concat", enum_flat_map, 0); rb_define_method(rb_mEnumerable, "inject", enum_inject, -1); rb_define_method(rb_mEnumerable, "reduce", enum_inject, -1); rb_define_method(rb_mEnumerable, "partition", enum_partition, 0);