如何使用校正因子创建哈希差异?

时间:2011-02-23 12:15:23

标签: ruby hash

我想比较数组中的哈希值:

h_array = [
  {:name => "John", :age => 23, :eye_color => "blue"},
  {:name => "John", :age => 22, :eye_color => "green"},
  {:name => "John", :age => 22, :eye_color => "black"}
]

get_diff(h_array, correct_factor = 2)
# should return [{:eye_color => "blue"}, {:eye_color => "green"}, {:eye_color => "black"}]

get_diff(h_array, correct_factor = 3)
# should return 
# [[{:age => 23}, {:age => 22}, {:age => 22}], 
# [{:eye_color => "blue"}, {:eye_color => "green"}, {:eye_color => "black"}]]

我想区分h_array中包含的哈希值。它看起来像递归调用/方法,因为h_array可以有多个哈希值但具有相同数量的键和值。如何实现get_diff方法?

3 个答案:

答案 0 :(得分:1)

def get_diff h_array, correct_factor
  h_array.first.keys.reject{|k|
    h_array.map{|h| h[k]}.sort.chunk{|e| e}.map{|_,e| e.size}.max >= correct_factor
  }.map{|k|
    h_array.map{|hash| hash.select{|key,_| k == key}}
  }
end

答案 1 :(得分:0)

class Array
   def find_ndups     # also returns the number of items
      uniq.map { |v| diff = (self.size - (self-[v]).size); (diff > 1) ? [v, diff] : nil}.compact
   end
end
h_array = [
  {:name => "John", :age => 22, :eye_color => "blue", :hair => "black"},
  {:name => "John", :age => 33, :eye_color => "orange", :hair => "green"},
  {:name => "John", :age => 22, :eye_color => "black", :hair => "yello"}
]
def get_diff(h_array, correct_factor)
  temp = h_array.inject([]){|result, element| result << element.to_a}
  master_array = []
  unmatched_arr = []
  matched_arr = []
  temp = temp.transpose
  temp.each_with_index do |arr, index|
    ee = arr.find_ndups
    if ee.length == 0
      unmatched_arr << temp[index].inject([]){|result, arr| result << {arr.first => arr.last} }

    elsif ee.length > 0  && ee[0][1] != correct_factor && ee[0][1] < correct_factor
      return_arr << temp[index].inject([]){|result, arr| result << {arr.first => arr.last} }
    elsif ee[0][1] = correct_factor
      matched_arr  << temp[index].inject([]){|result, arr| result << {arr.first => arr.last} }
    end

  end
  return [matched_arr, unmatched_arr]
end

puts get_diff(h_array, 2).inspect

希望有所帮助

答案 2 :(得分:0)

找到了ActiveSupport::CoreExtensions::Hash::Diff module。 ActiveSupport 2.3.2和2.3.4有一个内置的Hash :: Diff模块,它返回一个表示两个哈希值之间差异的哈希值。