summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--ChangeLog5
-rw-r--r--array.c44
-rw-r--r--test/ruby/test_array.rb8
3 files changed, 57 insertions, 0 deletions
diff --git a/ChangeLog b/ChangeLog
index edb7d17fcd..b890895372 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,8 @@
+Wed May 14 12:42:36 2008 Akinori MUSHA <knu@iDaemons.org>
+
+ * array.c (rb_ary_count): Override Enumerable#count for better
+ performance.
+
Wed May 14 11:29:06 2008 Koichi Sasada <ko1@atdot.net>
* insns.def: add a "putcbase" instruction.
diff --git a/array.c b/array.c
index 9fe0fc9c1b..631080d521 100644
--- a/array.c
+++ b/array.c
@@ -2776,6 +2776,49 @@ rb_ary_nitems(VALUE ary)
return LONG2NUM(n);
}
+/*
+ * call-seq:
+ * array.count(obj) -> int
+ * array.count { |item| block } -> int
+ *
+ * Returns the number of elements which equals to <i>obj</i>.
+ * If a block is given, counts tthe number of elements yielding a true value.
+ *
+ * ary = [1, 2, 4, 2]
+ * ary.count(2) # => 2
+ * ary.count{|x|x%2==0} # => 3
+ *
+ */
+
+static VALUE
+rb_ary_count(int argc, VALUE *argv, VALUE ary)
+{
+ long n = 0;
+
+ if (argc == 0) {
+ VALUE *p, *pend;
+
+ RETURN_ENUMERATOR(ary, 0, 0);
+
+ for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
+ if (RTEST(rb_yield(*p))) n++;
+ }
+ }
+ else {
+ VALUE obj, *p, *pend;
+
+ rb_scan_args(argc, argv, "1", &obj);
+ if (rb_block_given_p()) {
+ rb_warn("given block not used");
+ }
+ for (p = RARRAY_PTR(ary), pend = p + RARRAY_LEN(ary); p < pend; p++) {
+ if (rb_equal(*p, obj)) n++;
+ }
+ }
+
+ return LONG2NUM(n);
+}
+
static VALUE
flatten(VALUE ary, int level, int *modified)
{
@@ -3461,6 +3504,7 @@ Init_Array(void)
rb_define_method(rb_cArray, "flatten", rb_ary_flatten, -1);
rb_define_method(rb_cArray, "flatten!", rb_ary_flatten_bang, -1);
rb_define_method(rb_cArray, "nitems", rb_ary_nitems, 0);
+ rb_define_method(rb_cArray, "count", rb_ary_count, -1);
rb_define_method(rb_cArray, "shuffle!", rb_ary_shuffle_bang, 0);
rb_define_method(rb_cArray, "shuffle", rb_ary_shuffle, 0);
rb_define_method(rb_cArray, "choice", rb_ary_choice, 0);
diff --git a/test/ruby/test_array.rb b/test/ruby/test_array.rb
index 3775c1f54e..a5b4735601 100644
--- a/test/ruby/test_array.rb
+++ b/test/ruby/test_array.rb
@@ -537,6 +537,14 @@ class TestArray < Test::Unit::TestCase
assert_equal([1, 2, 3, 1, 2, 3], a)
end
+ def test_count
+ a = @cls[1, 2, 3, 1, 2]
+ assert_equal(2, a.count(1))
+ assert_equal(3, a.count {|x| x % 2 == 1 })
+ assert_equal(2, a.count(1) {|x| x % 2 == 1 })
+ assert_raise(ArgumentError) { a.count(0, 1) }
+ end
+
def test_delete
a = @cls[*('cab'..'cat').to_a]
assert_equal('cap', a.delete('cap'))