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

Set two keys for one value in Hash in Rails

提问人:unnamed_road 提问时间:8/24/2023 最后编辑:mechnicovunnamed_road 更新时间:8/25/2023 访问量:50

问:

假设我有一个哈希值:

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

在此期间,我需要消除重复项,因此它应该是其中之一或唯一。是否有可能有一些解决方法,例如:.mapfirstsecond

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

如果没有,如何根据条件删除哈希中的键重复项?是否可以将条件传递到块中?.uniq

谢谢

Ruby-on-Rails Ruby-on-Rails-5 Ruby-hash

评论


答:

1赞 David 8/24/2023 #1

是的,可以将块传递给该方法。#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}

评论

0赞 unnamed_road 8/24/2023
谢谢!是否有可能对他们俩都有第二个建议,而取消了唯一的建议?因此,例如,如果 hash[:first] 为 nil,我会使用 hash[:second] 代替?nil
0赞 David 8/24/2023
你指的是?您可以调用以删除所有值。hash.uniq(&:last)#select(&:last)nil
1赞 mechnicov 8/25/2023
uniq返回数组,因此需要将其转换为哈希值
1赞 nitsas 8/25/2023 #2

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

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

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

然后,您可以迭代它或以任何您喜欢的方式使用它。

评论

0赞 mechnicov 8/25/2023
好主意,但据我了解,OP 想要第一个价值
2赞 mechnicov 8/25/2023 #3
hsh =
  {
    first: :value1,
    second: :value1,
    third: :value2 
  }

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

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

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

并将数组转换为哈希

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