具有Ruby中的校正因子的哈希差异,用于动态哈希

时间:2011-02-24 05:12:25

标签: ruby hash

与此问题相似How do I create a diff of hashes with a correction factor? 我想比较数组中的哈希值,但哈希值可以是动态的。

h_array = [
   {:roll => "1", :name => "saroj", :class => "mscit"}, 
   {:name => "saroj", :class => "Mscit", :roll => "12", :attendance => "P"}, 
   {:class => "Mscit", :roll => "12", :name => "saroj", :attendance => "F", :remarks => "something"}
]

get_diff(h_array, correct_factor = 2)
# should return
# matched :: {:class=>"Mscit", :roll=>"12", :name=>"saroj"},
# unmatched :: {:attendance=>"F", :remarks=>"something"}

get_diff(h_array, correct_factor = 3)
# should return 
# matched :: {:name=>"saroj"},
# unmatched :: {:class=>"Mscit", :roll=>"12", :attendance=>"F", :remarks=>"something"}

correct_factor是确定匹配多少键/值应匹配的数字。我想要的是一个diff函数,它返回匹配和不匹配的对。

1 个答案:

答案 0 :(得分:0)

def get_diff(input,correct_factor)
    input_hash_merged = Hash.new
    solution_hash = Hash.new
    input.select{ |x| input_hash_merged.merge!(x) }
    input_hash_merged.each do |k,v|
        arr = Array.new
        freq = Hash.new(0)
        input.select{ |x| arr << x[k] unless x[k].nil? }
        arr.select{ |x| freq[x] += 1 }
        max_element = arr.sort_by { |x| freq[x] }.last
        max_count = freq.values.sort.last
        solution_hash[k] = max_element unless max_count < correct_factor
    end
    unmatched_hash = input_hash_merged.reject{|k,v| !solution_hash[k].nil?} 
    p solution_hash
    p unmatched_hash
end