From 86d05f81fd01c674ace8290e376c026c35b07d2c Mon Sep 17 00:00:00 2001 From: knu Date: Mon, 7 Apr 2008 12:40:45 +0000 Subject: * array.c (rb_ary_nitems): Backport Array#nitems with a block; suggested by Bertram Scharpf in [ruby-talk:134083]. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@15917 b2dd03c8-39d4-4d8f-98ff-823fe69b080e --- array.c | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) (limited to 'array.c') diff --git a/array.c b/array.c index c3aeefe372..2d345dab5d 100644 --- a/array.c +++ b/array.c @@ -2856,11 +2856,16 @@ rb_ary_compact(ary) /* * call-seq: * array.nitems -> int + * array.nitems { |item| block } -> int * * Returns the number of non-nil elements in _self_. + * If a block is given, the elements yielding a true value are + * counted. + * * May be zero. * * [ 1, nil, 3, nil, 5 ].nitems #=> 3 + * [5,6,7,8,9].nitems { |x| x % 2 != 0 } #=> 3 */ static VALUE @@ -2868,14 +2873,23 @@ rb_ary_nitems(ary) VALUE ary; { long n = 0; - VALUE *p, *pend; + + if (rb_block_given_p()) { + long i; - p = RARRAY(ary)->ptr; - pend = p + RARRAY(ary)->len; + for (i=0; i