ruby 在Rails的Hash中为一个值设置两个键

3zwjbxry  于 12个月前  发布在  Ruby
关注(0)|答案(3)|浏览(94)

假设我有一个hash:

{
  first: :value1,
  second: :value1,
  third: :value2 
}

.map期间,我需要消除重复,因此它应该是firstsecond。是否可以有一些变通办法,如:

{
  (:first || :second) => :value1,
  third: :value2 
}

如果没有,我如何根据条件删除哈希中的密钥重复项?是否可以将条件传入.uniq块?
谢谢你,

vybvopom

vybvopom1#

hsh =
  {
    first: :value1,
    second: :value1,
    third: :value2 
  }

hsh.uniq { _2 }.to_h
# => {:first=>:value1, :third=>:value2}

首先调用带有block和编号参数的uniq。它返回数组的数组,其中第二个元素是唯一的(取第一对)

ary = hsh.uniq { _2 }
# => [[:first, :value1], [:third, :value2]]

并将数组转换为哈希

ary.to_h
# => {:first=>:value1, :third=>:value2}
xfyts7mz

xfyts7mz2#

是的,可以将一个块传递给#uniq方法。
https://ruby-doc.org/3.2.2/Enumerable.html#method-i-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}
twh00eeo

twh00eeo3#

您还可以使用Hash#invert,使哈希点从每个唯一值指向单个键。它将保留每个值的最后一个键:

hash = {
  first: :value1,
  second: :value1,
  third: :value2 
}

hash.invert
# => {
#   :value1=> :second,
#   :value2=> :third
# }

然后你可以忽略它或者用任何你喜欢的方式。

相关问题