假设我在Ruby中有以下哈希数组:
a = [{:id => 1, :species =>"Homo sapiens"},
{:id => 2, :species =>"Canis lupus"},
{:id => 3, :species =>"Bos taurus"},
{:id => 4, :species =>"Homo sapiens"},
{:id => 5, :species =>"Pan troglodytes"},
{:id => 6, :species =>"Bos taurus"}]
只保留包含每个:species
键的第一个元素(即丢弃重复物种名称的任何元素)的最惯用和简洁的方法是什么?对于上面的示例,期望的结果将如下所示:
b = [{:id => 1, :species =>"Homo sapiens"},
{:id => 2, :species =>"Canis lupus"},
{:id => 3, :species =>"Bos taurus"},
{:id => 5, :species =>"Pan troglodytes"}]
我可以通过首先将所有物种读入第二个数组,删除带有uniq!
的重复项,然后遍历原始数组,以获得包含第二个数组中表示的每个物种的第一个元素来完成此操作,但这似乎非常不喜欢Ruby,看起来很难看。
答案 0 :(得分:7)
您只需使用Array#uniq
: -
a = [{:id => 1, :species =>"Homo sapiens"},
{:id => 2, :species =>"Canis lupus"},
{:id => 3, :species =>"Bos taurus"},
{:id => 4, :species =>"Homo sapiens"},
{:id => 5, :species =>"Pan troglodytes"},
{:id => 6, :species =>"Bos taurus"}]
a.uniq { |h| h[:species] }
# => [{:id=>1, :species=>"Homo sapiens"},
# {:id=>2, :species=>"Canis lupus"},
# {:id=>3, :species=>"Bos taurus"},
# {:id=>5, :species=>"Pan troglodytes"}]