I just noticed that Ruby does not throw an exception or even not give a warning if you add duplicate keys to the hash:
$VERBOSE = true key_value_pairs_with_duplicates = [[1,"a"], [1, "b"]] # No warning produced Hash[key_value_pairs_with_duplicates] # => {1=>"b"} # Also no warning hash_created_by_literal_with_duplicate_keys = {1 => "a", 1=> "b"} # => {1=>"b"}
For key_value_pairs_with_duplicates I could detect duplicate keys by doing
keys = key_value_pairs_with_duplicates.map(&:first) raise "Duplicate keys" unless keys.uniq == keys
Or by doing
procedurally_produced_hash = {} key_value_pairs_with_duplicates.each do |key, value| raise "Duplicate key" if procedurally_produced_hash.has_key?(key) procedurally_produced_hash[key] = value end
or
hash = Hash[key_value_pairs_with_duplicates] raise "Duplicate keys" unless hash.length == key_value_pairs_with_duplicates.length
But is there an idiomatic way to do this?
source share