NothingToSeeHere NothingToSeeHere - 15 days ago 4x
Ruby Question

Finding blank arrays within ruby arrays Rails 4

I am trying build a sentence out of 3 arrays with the count of each array.

cats = Cat.all
dogs = Dog.all
birds = Bird.all

animals = ["#{cats.count} Cats", "#{dogs.count} Dogs", "#{birds.count} Birds"]

sentence ={ |r| r }.join(", ")

Right now, this works, but if I have no cats sentence outputs to

"O Cats, 5 Dogs, 4 Birds"

and I'ld like it to just say:

"5 Dogs & 4 Birds"

or, at the very least:

"5 Dogs, 4 Birds"

I feel like I might need to use an array of hashes, but I'm a bit lost.


Yes, you need a hash.

cats = Cat.all 
dogs = Dog.all
birds = Bird.all

animals = {
  cats: cats.count,
  dogs: dogs.count,
  birds: birds.count

sentence = animals.reject{|k, v| v == 0}
                  .map{|k, v| "#{v} #{k.to_s.capitalize}"}
                  .join(', ')

My suggestion: keep data as data till the last moment, so that you can have maximum flexibility to display it in various ways. I feel that the animals in your code thinks rendering too soon.