[前][次][番号順一覧][スレッド一覧]

ruby-changes:13671

From: matz <ko1@a...>
Date: Sun, 25 Oct 2009 02:02:09 +0900 (JST)
Subject: [ruby-changes:13671] Ruby:r25456 (trunk): * enum.c (enum_flat_map): new method that concatenates the values

matz	2009-10-25 02:01:38 +0900 (Sun, 25 Oct 2009)

  New Revision: 25456

  http://svn.ruby-lang.org/cgi-bin/viewvc.cgi?view=rev&revision=25456

  Log:
    * enum.c (enum_flat_map): new method that concatenates the values
      from given block.  also provides alias #collect_concat.

  Modified files:
    trunk/ChangeLog
    trunk/enum.c

Index: ChangeLog
===================================================================
--- ChangeLog	(revision 25455)
+++ ChangeLog	(revision 25456)
@@ -7,6 +7,11 @@
 
 	* object.c (rb_obj_cmp): defines Object#<=>.  [ruby-core:24063]
 
+Sat Oct 24 09:51:28 2009  Yukihiro Matsumoto  <matz@r...>
+
+	* 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  <akr@f...>
 
 	* io.c (io_cntl): update max file descriptor by the result of
Index: enum.c
===================================================================
--- enum.c	(revision 25455)
+++ enum.c	(revision 25456)
@@ -396,8 +396,50 @@
     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
+ *  <em>block</em> once for every element in <i>enum</i>.
+ *
+ *     [[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
  *     enum.entries   =>    array
  *
@@ -2375,6 +2417,8 @@
     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);

--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/

[前][次][番号順一覧][スレッド一覧]