Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - How to pluralize a sentence? [duplicate]

I know you can pluralize a word in Rails using the pluralize feature.

pluralize (3, 'cat')
=> 3 cats

But what I'm trying to do is pluralize a sentence that needs to pluralize multiple words.

There are <%= Cat.count %> cats

The problem with this, is if there is only 1 cat. It would return

There are 1 cats

Which doesn't make sense gramatically.

It should say

There are x cats (if x is not 1)

There is 1 cat (if there is only 1)

Problem is, I can't figure out how to pluralize this, since we have two arguments here (is and cat).

Any help will be appreciated.

Maybe something like this?

if Cat.count == 1
  puts "There is 1 cat"
else
  puts "There are #{Cat.count} cats"
end
like image 974
Darkmouse Avatar asked Jul 31 '14 16:07

Darkmouse


1 Answers

You can make use of the pluralization features of the I18n library by defining count values to translation keys (i.e. config/locales/en.yml):

en:
  cats:
    one: 'There is one cat.'
    other: 'There are %{count} cats.'

Then, in your code (or view, or anywhere else, since I18n is globally available)

3.times{|i|
  puts I18n.t('cats', count: i)
}

will output

There are 0 cats.
There is one cat.
There are 2 cats.
like image 128
DMKE Avatar answered Oct 05 '22 23:10

DMKE