partition_by
From:
Florian Frank <flori@...>
Date:
2002-11-16 12:40:09 UTC
List:
ruby-core #577
Hi!
(0..9).partition_by { |x| x % 3 }
==>{0=>[0, 3, 6, 9], 1=>[1, 4, 7], 2=>[2, 5, 8]}
["abc","defg","123","a","xyz","mnop"].partition_by { |x| x.size }
==>{1=>["a"], 3=>["abc", "123", "xyz"], 4=>["defg", "mnop"]}
["abc","bcd","abcde","cdef","bc","abcdef"].partition_by { |x| x[0] }
==>{99=>["cdef"], 97=>["abc", "abcde", "abcdef"], 98=>["bcd", "bc"]}
What do you think?
--
It makes no difference who you vote for - the two parties are really one party
representing four percent of the people.
-- Gore Vidal
Attachments (1)
enum-part.patch
(1.26 KB, text/x-diff)
Index: enum.c
===================================================================
RCS file: /src/ruby/enum.c,v
retrieving revision 1.29
diff -u -p -p -u -r1.29 enum.c
--- enum.c 1 Aug 2002 09:42:36 -0000 1.29
+++ enum.c 25 Oct 2002 15:50:30 -0000
@@ -239,6 +239,32 @@ enum_partition(obj)
}
static VALUE
+partition_by_i(i, hash)
+ VALUE i, hash;
+{
+ VALUE key = rb_yield(i);
+ VALUE ref = rb_hash_aref(hash, key);
+
+ if (ref == RHASH(hash)->ifnone) {
+ ref = rb_ary_new();
+ rb_hash_aset(hash, key, ref);
+ }
+ rb_ary_push(ref, i);
+ return Qnil;
+}
+
+static VALUE
+enum_partition_by(obj)
+ VALUE obj;
+{
+ VALUE hash = rb_hash_new();
+
+ rb_iterate(rb_each, obj, partition_by_i, (VALUE)hash);
+
+ return hash;
+}
+
+static VALUE
enum_sort(obj)
VALUE obj;
{
@@ -506,6 +532,7 @@ Init_Enumerable()
rb_define_method(rb_mEnumerable,"map", enum_collect, 0);
rb_define_method(rb_mEnumerable,"inject", enum_inject, -1);
rb_define_method(rb_mEnumerable,"partition", enum_partition, 0);
+ rb_define_method(rb_mEnumerable,"partition_by", enum_partition_by, 0);
rb_define_method(rb_mEnumerable,"all?", enum_all, 0);
rb_define_method(rb_mEnumerable,"any?", enum_any, 0);
rb_define_method(rb_mEnumerable,"min", enum_min, 0);