本帖最后由 taroxd 于 2015-9-20 12:10 编辑  
 
随手写的,可能出错,只看思路就好 
 
# a, b 为两个具有 features 的物品 def compare_item(a, b)   # 为了更快速地索引,   # 制作一个 code => data_id => [value_a, value_b] 的表。   # 返回值即为这个 hash   result = Hash.new do |h1, code|     h1[code] = Hash.new do |h2, data_id|       h2[data_id] = []     end   end     a.features.each do |feature|     result[feature.code][feature.data_id][0] = feature.value   end     b.features.each do |feature|     result[feature.code][feature.data_id][1] = feature.value   end     result     # 获取结果后的用法:   # result.each do |code, data_id2value|   #   data_id2value.each do |data_id, (value_a, value_b)|   #   #     # value_a 和 value_b 可能为 nil。此时取 0 还是取 1 需要看情况判断。   #     # 在这里按照你的要求取 0。   #     value_a ||= 0   #     value_b ||= 0   #   #     do_something_with code, data_id, value_a - value_b   #   end   # end end 
 
 # a, b 为两个具有 features 的物品  
def compare_item(a, b)  
  # 为了更快速地索引,  
  # 制作一个 code => data_id => [value_a, value_b] 的表。  
  # 返回值即为这个 hash  
  result = Hash.new do |h1, code|  
    h1[code] = Hash.new do |h2, data_id|  
      h2[data_id] = []  
    end  
  end  
   
  a.features.each do |feature|  
    result[feature.code][feature.data_id][0] = feature.value  
  end  
   
  b.features.each do |feature|  
    result[feature.code][feature.data_id][1] = feature.value  
  end  
   
  result  
   
  # 获取结果后的用法:  
  # result.each do |code, data_id2value|  
  #   data_id2value.each do |data_id, (value_a, value_b)|  
  #  
  #     # value_a 和 value_b 可能为 nil。此时取 0 还是取 1 需要看情况判断。  
  #     # 在这里按照你的要求取 0。  
  #     value_a ||= 0  
  #     value_b ||= 0  
  #  
  #     do_something_with code, data_id, value_a - value_b  
  #   end  
  # end  
end  
 
  |