Feature #2321 ยป add_array_sum_and_mean_with_u.diff
array.c 2009-10-31 19:44:04.000000000 -0400 | ||
---|---|---|
}
|
||
}
|
||
# define ARY_SHARED_P(ary) \
|
||
(assert(!FL_TEST(ary, ELTS_SHARED) || !FL_TEST(ary, RARRAY_EMBED_FLAG)), \
|
||
FL_TEST(ary,ELTS_SHARED)!=0)
|
||
... | ... | |
/*
|
||
* call-seq:
|
||
* array.sum -> double
|
||
*
|
||
* Finds the sum of all the values in <i>self</i>.
|
||
* All of the values must be numbers,
|
||
* otherwise, the function raises a TypeError.
|
||
*
|
||
* a = [1, 2, 3]
|
||
* a.sum #=> 6
|
||
*
|
||
*
|
||
*/
|
||
static VALUE
|
||
rb_ary_sum(VALUE ary)
|
||
{
|
||
long i;
|
||
double sum = 0.0;
|
||
|
||
|
||
for (i=0; i<RARRAY_LEN(ary); i++) {
|
||
if( TYPE(RARRAY_PTR(ary)[i]) == T_STRING) {
|
||
rb_raise(rb_eTypeError, "Element is not a number!");
|
||
} else {
|
||
sum = sum + NUM2DBL(RARRAY_PTR(ary)[i]);
|
||
}
|
||
}
|
||
return DBL2NUM(sum);
|
||
}
|
||
/*
|
||
* call-seq:
|
||
* array.mean -> double
|
||
*
|
||
* Finds the mean of values in <i>self</i>. All values must be numbers,
|
||
* otherwise, the function raises a TypeError.
|
||
*
|
||
* a = [1, 2, 3]
|
||
* a.mean #=> 2
|
||
*
|
||
*/
|
||
|
||
static VALUE
|
||
rb_ary_mean(VALUE ary)
|
||
{
|
||
return DBL2NUM(NUM2DBL(rb_ary_sum(ary)) / RARRAY_LEN(ary));
|
||
}
|
||
/*
|
||
* call-seq:
|
||
* array.each_index {|index| block } -> array
|
||
*
|
||
* Same as <code>Array#each</code>, but passes the index of the element
|
||
... | ... | |
rb_define_method(rb_cArray, "take_while", rb_ary_take_while, 0);
|
||
rb_define_method(rb_cArray, "drop", rb_ary_drop, 1);
|
||
rb_define_method(rb_cArray, "drop_while", rb_ary_drop_while, 0);
|
||
|
||
rb_define_method(rb_cArray, "sum", rb_ary_sum, 0);
|
||
rb_define_method(rb_cArray, "mean", rb_ary_mean, 0);
|
||
id_cmp = rb_intern("<=>");
|
||
}
|