按键值排列的唯一哈希数组
Unique array of hashes by key value
好的,所以...我有一个这样的哈希数组:
[
{ :id => 0, :text => "someText" },
{ :id => 1, :text => "anotherText" },
{ :id => 2, :text => "someText" }
]
我想要的是 filter
散列并删除重复的 :text
值,因此结果是:
[
{ :id => 0, :text => "someText" },
{ :id => 1, :text => "anotherText" }
]
我该怎么做?
P.S。当然,我可以想办法去做。我要求的是最好(也是最快)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"}]
将有许多不同的方法来实现您的目标,但是当您正在寻找最快的方法时,这里是 uniq 和 [=24= 的基准]。这仅供示例。像这样你可以测试自己不同的方法并根据你的要求检查解决方案..
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
人们可能会在 select 那里设置任何条件,只有那些具有偶数 :id
的元素或其他元素。
好的,所以...我有一个这样的哈希数组:
[
{ :id => 0, :text => "someText" },
{ :id => 1, :text => "anotherText" },
{ :id => 2, :text => "someText" }
]
我想要的是 filter
散列并删除重复的 :text
值,因此结果是:
[
{ :id => 0, :text => "someText" },
{ :id => 1, :text => "anotherText" }
]
我该怎么做?
P.S。当然,我可以想办法去做。我要求的是最好(也是最快)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"}]
将有许多不同的方法来实现您的目标,但是当您正在寻找最快的方法时,这里是 uniq 和 [=24= 的基准]。这仅供示例。像这样你可以测试自己不同的方法并根据你的要求检查解决方案..
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
人们可能会在 select 那里设置任何条件,只有那些具有偶数 :id
的元素或其他元素。