I am trying to add the float values of a ruby array in C with RubyInline (ruby 1.9.2). The expected output should be a float value. Here is my code:
require 'inline'
class ArrayMath
inline :C do |builder|
builder.c "
VALUE sum(VALUE arr){
int size = RARRAY_LEN(arr);
VALUE *c_arr = RARRAY_PTR(arr);
int i, x;
float sum = 0.0;
for (i=0; i<size; i++)
{
x = NUM2DBL(c_arr[i]);
sum += x;
}
return( rb_float_new(sum) );
}"
end
end
running this in the console
ArrayMath.new.sum([1,2.7])
outputs 3.0
Obviously the expected result is 3.7
xis anintin your C code. Change that to afloat(ordouble) if you don’t want the result ofNUM2DBLtruncated.Or do away with that temporary altogether and write: