这是一个示例数组示例作为输入:
hashForAnimals = [{
:animalCd=>"Tiger",:animalType=>"Carnivore", :sortOrder =>3},
{:animalCd=>"Cow",:animalType=>"Herbivore", :sortOrder =>5},
{:animalCd=>"Rabbit", :animalType=>"Herbivore", :sortOrder =>2},
{:animalCd=>"Shark",:animalType=>"Carnivore", :sortOrder =>4},
{:animalCd=>"Cow",:animalType=>"Carnivore", :sortOrder =>1},
{:animalCd=>"Bear", :animalType=>"Omnivore", :sortOrder =>7},
{:animalCd=>"Tiger",:animalType=>"Carnivore", :sortOrder =>6}]
预期产出:
hashForAnimals = [{
:animalCd=>"Cow", :animalType=>"Carnivore", :sortOrder =>1},
{:animalCd=>"Rabbit", :animalType=>"Herbivore", :sortOrder =>2},
{:animalCd=>"Tiger",:animalType=>"Carnivore", :sortOrder =>3},
{:animalCd=>"Shark",:animalType=>"Carnivore", :sortOrder =>4},
:animalCd=>"Cow", :animalType=>"Herbivore", :sortOrder =>5}
{:animalCd=>"Bear", :animalType=>"Omnivore", :sortOrder =>7}]
我需要在排序顺序的基础上对数组进行排序,然后我需要使该数组在属于同一组(即animalType)的animalCd中是唯一的。
Tiger已经以最小排序顺序出现过一次,但是Cow在阵列中出现两次但是动物类型不同。
可以通过将数组收集到多个animalType数组中并对其进行排序并使其唯一并合并回单个数组来完成。但是,我需要一个优雅的解决方案。
我正在尝试的示例代码:
hashForAnimals.sort!{|x,y| x[:sortOrder].to_i<=>y[:sortOrder].to_i}.group_by { |a| a[:animalType]}
我可以将它们分成单独的哈希值,但之后我需要使单个哈希值唯一,然后合并到数组中。
这是否可能与我接近它的方式有关?
答案 0 :(得分:2)
您可以使用sort_by
方法和uniq
以及values_at
hashForAnimals.sort_by{ |a| a[:sortOrder] }.uniq{ |k| k.values_at(:animalCd, :animalType) }
# => [{:animalCd=>"Cow", :animalType=>"Carnivore", :sortOrder=>1}, {:animalCd=>"Rabbit", :animalType=>"Herbivore", :sortOrder=>2}, {:animalCd=>"Tiger", :animalType=>"Carnivore", :sortOrder=>3}, {:animalCd=>"Shark", :animalType=>"Carnivore", :sortOrder=>4}, {:animalCd=>"Cow", :animalType=>"Herbivore", :sortOrder=>5}, {:animalCd=>"Bear", :animalType=>"Omnivore", :sortOrder=>7}]