Ruby:根据两个键值的组合检测哈希中的重复

时间:2013-12-23 07:13:08

标签: ruby-on-rails ruby hash

我有以下哈希。我想检测具有相同from和值组合的哈希值。有没有办法在红宝石中有效地做到这一点?

attributes = {"0"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3"}, "1"=>{"from"=>"xxx", "to"=>"zzz", "value"=>"3.5"}, "2"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3.5"}}

这里属性[“2”]是属性[“0”]的重复(因为它们具有相同的from和to值)。我想检测这个并引发异常。任何人都可以帮助我吗?

3 个答案:

答案 0 :(得分:1)

尝试代码:

# => {"0"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3"}, "1"=>{"from"=>"xxx", "to"=>"zzz", "value"=>"3.5"}, "2"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3.5"}}

attributes.each do|k,a|
  sel = attributes.select {|_,b| b['from'] == a['from'] && b['to'] == a['to'] }
  p sel
  raise Exception if sel.size > 1
end

# {"0"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3"}, "2"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3.5"}}

答案 1 :(得分:1)

我会这样做:

attributes = {"0"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3"}, "1"=>{"from"=>"xxx", "to"=>"zzz", "value"=>"3.5"}, "2"=>{"from"=>"xxx", "to"=>"yyy", "value"=>"3.5"}}
bol = attributes.group_by{|_,v| v.values_at("from","value") }.any?{|_,v| v.size >= 2 }
raise "exception" if bol

答案 2 :(得分:1)

> valid = h.to_a.uniq {|a| [a.last['from'], a.last['to']] }.length == h.keys.length
=> false

raise 'hash is not unique' unless valid