mirror of
https://github.com/ruby/ruby.git
synced 2025-08-15 21:49:06 +02:00
* array.c (rb_ary_nitems): Backport Array#nitems with a block;
suggested by Bertram Scharpf <lists@bertram-scharpf.de> in [ruby-talk:134083]. git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/branches/ruby_1_8@15917 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
This commit is contained in:
parent
5e644b81b7
commit
86d05f81fd
3 changed files with 30 additions and 6 deletions
|
@ -1,3 +1,9 @@
|
|||
Mon Apr 7 21:35:08 2008 Akinori MUSHA <knu@iDaemons.org>
|
||||
|
||||
* array.c (rb_ary_nitems): Backport Array#nitems with a block;
|
||||
suggested by Bertram Scharpf <lists@bertram-scharpf.de> in
|
||||
[ruby-talk:134083].
|
||||
|
||||
Sun Apr 6 09:45:00 2008 Nobuyoshi Nakada <nobu@ruby-lang.org>
|
||||
|
||||
* dir.c (dir_tell): check if closed. [ruby-core:16223]
|
||||
|
|
4
NEWS
4
NEWS
|
@ -17,6 +17,10 @@ with all sufficient information, see the ChangeLog file.
|
|||
|
||||
* 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.
|
||||
|
|
20
array.c
20
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-<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,15 +2873,24 @@ rb_ary_nitems(ary)
|
|||
VALUE ary;
|
||||
{
|
||||
long n = 0;
|
||||
VALUE *p, *pend;
|
||||
|
||||
p = RARRAY(ary)->ptr;
|
||||
pend = p + RARRAY(ary)->len;
|
||||
if (rb_block_given_p()) {
|
||||
long i;
|
||||
|
||||
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++;
|
||||
}
|
||||
}
|
||||
return LONG2NUM(n);
|
||||
}
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue