按键值的唯一哈希数组



好的,那么…我有一个像这样的哈希数组:

[
    { :id => 0, :text => "someText" },
    { :id => 1, :text => "anotherText" },
    { :id => 2, :text => "someText" }
]

我想要的,是filter哈希与删除重复的:text值,使结果是:

[
    { :id => 0, :text => "someText" },
    { :id => 1, :text => "anotherText" }
]

我该怎么做呢?


注:当然,我能找到办法做到这一点。我所要求的是最好的。最快的)Ruby友好的方式,考虑到我不是Ruby大师。: -)

尝试使用 array# uniq:

arr.uniq{|h| h[:text]} # Returns a new array by removing duplicate values
 => [{:id=>0, :text=>"someText"}, {:id=>1, :text=>"anotherText"}]
# OR    
arr.uniq!{|h| h[:text]} # Removes duplicate elements from self.
=> [{:id=>0, :text=>"someText"}, {:id=>1, :text=>"anotherText"}]

有许多不同的方法来实现你的目标,但当你正在寻找最快的方式,这里是基准的uniqgroup_by。这只是样本。像这样,您可以测试自己不同的方法,并根据您的需求检查解决方案。
require 'benchmark'
arr = [{ :id => 0, :text => "someText" }, { :id => 1, :text => "anotherText" }, { :id => 2, :text => "someText" }]
Benchmark.bm do |x|
  x.report("group_by:")   { arr.group_by { |e| e[:text] }.values.map &:first }
  x.report("uniq:")   { arr.uniq{|h| h[:text]} }
end
# output
            user     system      total        real
group_by:  0.000000   0.000000   0.000000 (  0.000039)
uniq:      0.000000   0.000000   0.000000 (  0.000012)

虽然uniq是问题的完美解决方案,但有更灵活的方法,您可以指定从多个变体中挑选出的附加条件:

#                                        ⇓⇓⇓⇓⇓⇓⇓
arr.group_by { |e| e[:text] }.values.map &:first

可以在那里设置任何条件,仅选择具有偶数:id的元素或其他元素。

最新更新