gpt4 book ai didi

ruby - 在 Ruby 中检测重复键的惯用方法?

转载 作者:数据小太阳 更新时间:2023-10-29 07:19:31 25 4
gpt4 key购买 nike

我刚刚注意到,如果您向散列提供重复的键,Ruby 不会引发异常,甚至不会发出警告:

$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"}

对于key_value_pairs_with_duplicates,我可以检测重复键

keys = key_value_pairs_with_duplicates.map(&:first)
raise "Duplicate keys" unless keys.uniq == keys

或者通过做

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

或者

hash = Hash[key_value_pairs_with_duplicates]
raise "Duplicate keys" unless hash.length == key_value_pairs_with_duplicates.length

但是有没有一种惯用的方法呢?

最佳答案

Hash#merge 采用可选 block 来定义如何处理重复键。

http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-merge

利用此 block 仅在重复键上调用这一事实:

>> a = {a: 1, b: 2}
=> {:a=>1, :b=>2}

>> a.merge(c: 3) { |key, old, new| fail "Duplicate key: #{key}" }
=> {:a=>1, :b=>2, :c=>3}

>> a.merge(b: 10, c: 3) { |key, old, new| fail "Duplicate key: #{key}" }
RuntimeError: Duplicate key: b

关于ruby - 在 Ruby 中检测重复键的惯用方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8088342/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com