0
require 'inline'

class InlineTest
  inline(:C) do |builder|
    builder.c '
      VALUE arr_distance(VALUE arr1, VALUE arr2){
         long arr1_len = RARRAY_LEN(arr1);
         long arr2_len = RARRAY_LEN(arr2);
         if(arr1_len == 0 || arr2_len == 0){
           return 0.0;
         }
         else{
           long i, j;
           int count = 0;
           VALUE *c_arr1 = RARRAY_PTR(arr1);
           VALUE *c_arr2 = RARRAY_PTR(arr2);
           for(i = 0; i < arr1_len; i++){
             for(j = 0; j < arr2_len; j++){
               if(rb_str_cmp(c_arr1[i], c_arr2[j]) == 0){
                 count++;
               }
             }
           }
           VALUE arr1_match = count/arr1_len;
           VALUE arr2_match = count/arr2_len;
           VALUE match_percent = (arr2_match * 10 + arr1_match) / 11.0;
           return match_percent; //This does not return double value.
        }
     }'
  end
end

p InlineTest.new.arr_distance(['1', '2', '3'], ['1', '2', '3']) # => 0

我使用上述逻辑来计算我的匹配百分比。

上面的示例代码打印0。我希望它打印出来1.0

4

1 回答 1

1

使用DBL2NUM

builder.c '
  VALUE arr_distance(VALUE arr1, VALUE arr2){            
      long arr1_len = RARRAY_LEN(arr1);
      long arr2_len = RARRAY_LEN(arr2);            
      if(arr1_len == 0 || arr2_len == 0){
        return DBL2NUM(0.0); /* <------------ */
      }
      else{
        long i, j;
        int count = 0;
        VALUE *c_arr1 = RARRAY_PTR(arr1);
        VALUE *c_arr2 = RARRAY_PTR(arr2);

        for(i = 0; i < arr1_len; i++){
          for(j = 0; j < arr2_len; j++){
            if(rb_str_cmp(c_arr1[i], c_arr2[j]) == 0){
              count++;
            }
          }
        }

        VALUE arr1_match = count/arr1_len;
        VALUE arr2_match = count/arr2_len;
        double match_percent = (arr2_match * 10 + arr1_match) / 11.0;
        return DBL2NUM(match_percent); /* <------------- */
    }            
  }'
  • 不要0.0直接返回。
  • 不要VALUE用于存储 C 数值。
于 2013-11-07T07:37:32.387 回答