简化将具有最高计数的字典值添加到数组的代码

时间:2018-07-03 21:49:33

标签: ruby-on-rails ruby

我有很多个体动物和一系列相关物种。我想将更多的猫和狗添加到我的一系列相关物种中。个别动物的阵列可能没有所请求的物种,在这种情况下,物种数量返回{}

species_count吸收了一系列动物,并按物种将它们分组。示例:

animals = ['chihuaha', 'german_shepherd', 'golden_retriever', 'tabby cat', 'siamese cat'}
species_count(animals, DOG) = { species: 'dog', count: 3 }
species_count(animals, CAT) = { species: 'cat', count: 3 }
species_count(animals, MOUSE) = {}

我认为以下内容可以改进。 Ruby拥有各种神奇的方法,这些使我感到惊讶。

dogs = species_count(animals, DOG)
dog_count = dogs.fetch(:count, 0)
cats = species_count(animals, CAT)
cat_count = cats.fetch(:count, 0)

if dog_count >= cat_count && dog_count >= 3
    relevant_species << dogs
elsif cat_count >= 3
    relevant_species << cats
end

1 个答案:

答案 0 :(得分:1)

可能是这样的事情:

简化代码:

relevant_species = [DOG, CAT, MOUSE]
  .map { |animal| species_count(animals, animal) }
  .sort { |a, b| a[:count].to_i <=> b[:count].to_i }
  .last

或逐步操作:

# returns array of [{ species: 'dog', count: 3 }, ... ]
species_counts = [DOG, CAT, MOUSE].map { |animal| species_count(animals, animal) }

# sorts the array based on the count value. to_i is to account for nils
sorted_species_counts = species_counts.sort { |a, b| a[:count].to_i <=> b[:count].to_i }

# returns the last element (with the highest count value) to be assigned to relevant species
relevant_species = sorted_species_counts.last