{}
。
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
答案 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