From 645890629294602cf7722e7667ea10eb067697ff Mon Sep 17 00:00:00 2001 From: matz Date: Sun, 5 Feb 2006 15:26:53 +0000 Subject: [PATCH] * enum.c (enum_find_index): a new method Enumerable#find_index. [ruby-talk:178495] git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@9898 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- ChangeLog | 5 +++++ enum.c | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 45 insertions(+) diff --git a/ChangeLog b/ChangeLog index 18c229d03c..c02bc2978b 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,8 @@ +Mon Feb 6 00:14:57 2006 Yukihiro Matsumoto + + * enum.c (enum_find_index): a new method Enumerable#find_index. + [ruby-talk:178495] + Sun Feb 5 23:29:31 2006 Tanaka Akira * ruby.h (struct RStruct): embed 3 or less elements structs. diff --git a/enum.c b/enum.c index 1cefb6db18..5fdde385f7 100644 --- a/enum.c +++ b/enum.c @@ -165,6 +165,45 @@ enum_find(int argc, VALUE *argv, VALUE obj) return Qnil; } +static VALUE +find_index_i(VALUE i, VALUE *memo) +{ + if (RTEST(rb_yield(i))) { + memo[0] = UINT2NUM(memo[1]); + rb_iter_break(); + } + memo[1]++; + return Qnil; +} + +/* + * call-seq: + * enum.find_index(ifnone = nil) {| obj | block } => int + * + * Passes each entry in enum to block. Returns the + * index for the first for which block is not false. + * If no object matches, returns nil + * + * (1..10).find_index {|i| i % 5 == 0 and i % 7 == 0 } #=> nil + * (1..100).find_index {|i| i % 5 == 0 and i % 7 == 0 } #=> 35 + * + */ + +static VALUE +enum_find_index(VALUE obj) +{ + VALUE memo[2]; + + RETURN_ENUMERATOR(obj, 0, 0); + memo[0] = Qundef; + memo[1] = 0; + rb_block_call(obj, id_each, 0, 0, find_index_i, (VALUE)memo); + if (memo[0] != Qundef) { + return memo[0]; + } + return Qnil; +} + static VALUE find_all_i(VALUE i, VALUE ary) { @@ -1173,6 +1212,7 @@ Init_Enumerable(void) rb_define_method(rb_mEnumerable,"count", enum_count, -1); rb_define_method(rb_mEnumerable,"find", enum_find, -1); rb_define_method(rb_mEnumerable,"detect", enum_find, -1); + rb_define_method(rb_mEnumerable,"find_index", enum_find_index, 0); rb_define_method(rb_mEnumerable,"find_all", enum_find_all, 0); rb_define_method(rb_mEnumerable,"select", enum_find_all, 0); rb_define_method(rb_mEnumerable,"reject", enum_reject, 0);