假设我有一个hash:
{ first: :value1, second: :value1, third: :value2 }
在.map期间,我需要消除重复,因此它应该是first或second。是否可以有一些变通办法,如:
.map
first
second
{ (:first || :second) => :value1, third: :value2 }
如果没有,我如何根据条件删除哈希中的密钥重复项?是否可以将条件传入.uniq块?谢谢你,
.uniq
vybvopom1#
hsh = { first: :value1, second: :value1, third: :value2 } hsh.uniq { _2 }.to_h # => {:first=>:value1, :third=>:value2}
首先调用带有block和编号参数的uniq。它返回数组的数组,其中第二个元素是唯一的(取第一对)
uniq
ary = hsh.uniq { _2 } # => [[:first, :value1], [:third, :value2]]
并将数组转换为哈希
ary.to_h # => {:first=>:value1, :third=>:value2}
xfyts7mz2#
是的,可以将一个块传递给#uniq方法。https://ruby-doc.org/3.2.2/Enumerable.html#method-i-uniq您可以应用以下内容:
#uniq
hash.uniq { |_k, v| v }
或更短:
hash.uniq(&:last)
另外,如果你不需要键,另一个正确的解决方案是简单地获取值:
hash.values.uniq
你的第二个建议是有效的Ruby代码,但不正确,因为它删除了一个键,并评估为:
irb(main):004:0> { (:first || :second) => :value1, third: :value2 } => {:first=>:value1, :third=>:value2}
twh00eeo3#
您还可以使用Hash#invert,使哈希点从每个唯一值指向单个键。它将保留每个值的最后一个键:
Hash#invert
hash = { first: :value1, second: :value1, third: :value2 } hash.invert # => { # :value1=> :second, # :value2=> :third # }
然后你可以忽略它或者用任何你喜欢的方式。
3条答案
按热度按时间vybvopom1#
首先调用带有block和编号参数的
uniq
。它返回数组的数组,其中第二个元素是唯一的(取第一对)并将数组转换为哈希
xfyts7mz2#
是的,可以将一个块传递给
#uniq
方法。https://ruby-doc.org/3.2.2/Enumerable.html#method-i-uniq
您可以应用以下内容:
或更短:
另外,如果你不需要键,另一个正确的解决方案是简单地获取值:
你的第二个建议是有效的Ruby代码,但不正确,因为它删除了一个键,并评估为:
twh00eeo3#
您还可以使用
Hash#invert
,使哈希点从每个唯一值指向单个键。它将保留每个值的最后一个键:然后你可以忽略它或者用任何你喜欢的方式。