我想用3個數組中的每一個數組的數量構建一個句子。在ruby數組中查找空數組Rails 4
cats = Cat.all
dogs = Dog.all
birds = Bird.all
animals = ["#{cats.count} Cats", "#{dogs.count} Dogs", "#{birds.count} Birds"]
sentence = animals.each.map{ |r| r }.join(", ")
眼下,這個工作,但如果我沒有貓句子輸出到
"O Cats, 5 Dogs, 4 Birds"
和I'ld喜歡它,只是說:
"5 Dogs & 4 Birds"
,或者在至少:
"5 Dogs, 4 Birds"
我覺得我可能需要使用一組哈希值,但我有點失落。
更簡單的事情是將動物數組聲明爲'animals = []',然後像元素一樣添加:'animals <<「#{cats.count} Cats」if cats.count> 0'。這一切都取決於你的實現如何完成,所以,這可能適用於你,也可能不適合你。 – fanta