From 0453dc68e4694830d1a34d65f8ff8dcc4321f453 Mon Sep 17 00:00:00 2001 From: matz Date: Mon, 6 Aug 2007 16:26:17 +0000 Subject: * enum.c (enum_cycle): new method to cycle enumerable forever. git-svn-id: http://svn.ruby-lang.org/repos/ruby/trunk@12890 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- enum.c | 39 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) (limited to 'enum.c') diff --git a/enum.c b/enum.c index a93b171c0..3ca42ca4b 100644 --- a/enum.c +++ b/enum.c @@ -1526,6 +1526,44 @@ enum_drop(int argc, VALUE *argv, VALUE obj) return args[0]; } + +static VALUE +cycle_i(VALUE i, VALUE ary) +{ + rb_ary_push(ary, i); + rb_yield(i); + return Qnil; +} + +/* + * call-seq: + * enum.cycle {|obj| block } + * + * Calls block for each element of enumerable repeatedly + * forever. Enumerable#cycle saves elements in an internal array. + * + * a = ["a", "b", "c"] + * a.each {|x| puts x } # print, a, b, c, a, b, c,.. forever. + * + */ + +static VALUE +enum_cycle(VALUE obj) +{ + VALUE ary; + long i; + + RETURN_ENUMERATOR(obj, 0, 0); + ary = rb_ary_new(); + rb_block_call(obj, id_each, 0, 0, cycle_i, ary); + for (;;) { + for (i=0; iEnumerable mixin provides collection classes with * several traversal and searching methods, and with the ability to @@ -1578,6 +1616,7 @@ Init_Enumerable(void) rb_define_method(rb_mEnumerable, "zip", enum_zip, -1); rb_define_method(rb_mEnumerable, "take", enum_take, -1); rb_define_method(rb_mEnumerable, "drop", enum_drop, -1); + rb_define_method(rb_mEnumerable, "cycle", enum_cycle, 0); id_eqq = rb_intern("==="); id_each = rb_intern("each"); -- cgit