summaryrefslogtreecommitdiff
path: root/array.c
diff options
context:
space:
mode:
authormatz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2005-06-08 03:30:56 +0000
committermatz <matz@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2005-06-08 03:30:56 +0000
commit8d5e6a0fc68dbea9b7182d8e8dd9ac4a5b65af57 (patch)
treef4ca463a03a8ac0b5705df03ecf5a17e27de6f14 /array.c
parent5ef43814a8d1cf3b3905c70555b09255f37cf1e3 (diff)
* array.c (rb_ary_nitems): add the block feature to Array#nitems.
suggested by Bertram Scharpf <lists@bertram-scharpf.de> in [ruby-talk:134083]. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@8593 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'array.c')
-rw-r--r--array.c26
1 files changed, 20 insertions, 6 deletions
diff --git a/array.c b/array.c
index ceb68f5034..79547bee37 100644
--- a/array.c
+++ b/array.c
@@ -2890,11 +2890,16 @@ rb_ary_compact(ary)
/*
* call-seq:
* array.nitems -> int
+ * array.nitems { |item| block } -> int
*
* Returns the number of non-<code>nil</code> 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
@@ -2902,14 +2907,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<RARRAY(ary)->len; i++) {
+ VALUE v = RARRAY(ary)->ptr[i];
+ if (RTEST(rb_yield(v))) n++;
+ }
+ }
+ else {
+ VALUE *p = RARRAY(ary)->ptr;
+ VALUE *pend = p + RARRAY(ary)->len;
- while (p < pend) {
- if (!NIL_P(*p)) n++;
- p++;
+ while (p < pend) {
+ if (!NIL_P(*p)) n++;
+ p++;
+ }
}
return LONG2NUM(n);
}