ruby-changes:4426
From: ko1@a...
Date: Mon, 7 Apr 2008 21:41:03 +0900 (JST)
Subject: [ruby-changes:4426] knu - Ruby:r15917 (ruby_1_8): * array.c (rb_ary_nitems): Backport Array#nitems with a block;
knu 2008-04-07 21:40:45 +0900 (Mon, 07 Apr 2008)
New Revision: 15917
Modified files:
branches/ruby_1_8/ChangeLog
branches/ruby_1_8/NEWS
branches/ruby_1_8/array.c
Log:
* array.c (rb_ary_nitems): Backport Array#nitems with a block;
suggested by Bertram Scharpf <lists@b...> in
[ruby-talk:134083].
http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/branches/ruby_1_8/ChangeLog?r1=15917&r2=15916&diff_format=u
http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/branches/ruby_1_8/array.c?r1=15917&r2=15916&diff_format=u
http://svn.ruby-lang.org/cgi-bin/viewvc.cgi/branches/ruby_1_8/NEWS?r1=15917&r2=15916&diff_format=u
Index: ruby_1_8/array.c
===================================================================
--- ruby_1_8/array.c (revision 15916)
+++ ruby_1_8/array.c (revision 15917)
@@ -2856,11 +2856,16 @@
/*
* 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
@@ -2868,14 +2873,23 @@
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_LEN(ary); i++) {
+ VALUE v = RARRAY_PTR(ary)[i];
+ if (RTEST(rb_yield(v))) n++;
+ }
+ }
+ else {
+ VALUE *p = RARRAY_PTR(ary);
+ VALUE *pend = p + RARRAY_LEN(ary);
- while (p < pend) {
- if (!NIL_P(*p)) n++;
- p++;
+ while (p < pend) {
+ if (!NIL_P(*p)) n++;
+ p++;
+ }
}
return LONG2NUM(n);
}
Index: ruby_1_8/NEWS
===================================================================
--- ruby_1_8/NEWS (revision 15916)
+++ ruby_1_8/NEWS (revision 15917)
@@ -17,6 +17,10 @@
* builtin classes
+ * Array#nitems now takes a block optionally, which is used to
+ determine if each element should be counted instead of checking if
+ the element is non-nil.
+
* Integer#ord implemented.
* Integer#odd? implemented.
* Integer#even? implemented.
Index: ruby_1_8/ChangeLog
===================================================================
--- ruby_1_8/ChangeLog (revision 15916)
+++ ruby_1_8/ChangeLog (revision 15917)
@@ -1,3 +1,9 @@
+Mon Apr 7 21:35:08 2008 Akinori MUSHA <knu@i...>
+
+ * array.c (rb_ary_nitems): Backport Array#nitems with a block;
+ suggested by Bertram Scharpf <lists@b...> in
+ [ruby-talk:134083].
+
Sun Apr 6 09:45:00 2008 Nobuyoshi Nakada <nobu@r...>
* dir.c (dir_tell): check if closed. [ruby-core:16223]
--
ML: ruby-changes@q...
Info: http://www.atdot.net/~ko1/quickml/