From: Yusuke ENDOH <mame@...> Date: 2009-02-14T09:59:14+09:00 Subject: [ruby-dev:38002] Re: [Feature:1.9] Enumerable#uniq 遠藤です。 2009/02/13 22:17 Nobuyoshi Nakada <nobu@ruby-lang.org>: > なかだです。 > > Arrayだけでなく、Enumerableにもuniqがあってもいいんじゃないでしょ > うか。 私もいいと思います。 便乗ですが、Enumerable#compact もほしいです。 Index: enum.c =================================================================== --- enum.c (revision 22297) +++ enum.c (working copy) @@ -1793,6 +1793,32 @@ return Qnil; /* not reached */ } +static VALUE +compact_i(VALUE i, VALUE ary, int argc, VALUE *argv) +{ + VALUE val = enum_values_pack(argc, argv); + if (!NIL_P(val)) rb_ary_push(ary, val); + return Qnil; +} + +/* + * call-seq: + * enum.compact -> array + * + * Returns an array containing the items in <i>enum</i> with all +nil+ + * elements removed. + * + * [ "a", nil, "b", nil, "c" ].to_enum.compact #=> [ "a", "b", "c" ] + */ + +static VALUE +enum_compact(VALUE obj) +{ + VALUE ary = rb_ary_new(); + rb_block_call(obj, id_each, 0, 0, compact_i, ary); + return ary; +} + /* * The <code>Enumerable</code> mixin provides collection classes with * several traversal and searching methods, and with the ability to @@ -1852,6 +1878,7 @@ rb_define_method(rb_mEnumerable, "drop", enum_drop, 1); rb_define_method(rb_mEnumerable, "drop_while", enum_drop_while, 0); rb_define_method(rb_mEnumerable, "cycle", enum_cycle, -1); + rb_define_method(rb_mEnumerable, "compact", enum_compact, 0); id_eqq = rb_intern("==="); id_each = rb_intern("each"); -- Yusuke ENDOH <mame@tsg.ne.jp>