Ruby内联 - 返回双值

时间:2013-11-07 07:32:05

标签: ruby inline

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

1 个答案:

答案 0 :(得分: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数值。