How to pluralize “There is/are N object/objects”?

流过昼夜 提交于 2019-11-29 11:08:52

问题


Pluralizing a single word is simple:

pluralize(@total_users, "user")

But what if I want to print "There is/are N user/users":

There are 0 users
There is 1 user
There are 2 users

, i.e., how to pluralize a sentence?


回答1:


You can add a custom inflection for it. By default, Rails will add an inflections.rb to config/initializers. There you can add:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular "is", "are"
end

You will then be able to use pluralize(@total_users, "is") to return is/are using the same rules as user/users.

EDIT: You clarified the question on how to pluralize a sentence. This is much more difficult to do generically, but if you want to do it, you'll have to dive into NLP.

As the comment suggests, you could do something with I18n if you just want to do it with a few sentences, you could build something like this:

  def pluralize_sentence(count, i18n_id, plural_i18n_id = nil)
    if count == 1
      I18n.t(i18n_id, :count => count)
    else
      I18n.t(plural_i18n_id || (i18n_id + "_plural"), :count => count)
    end
  end

  pluralize_sentence(@total_users, "user_count")

And in config/locales/en.yml:

  en:
    user_count: "There is %{count} user."
    user_count_plural: "There are %{count} users."



回答2:


This is probably best covered by the Rails i18n pluralization features. Adapted from http://guides.rubyonrails.org/i18n.html#pluralization

I18n.backend.store_translations :en, :user_msg => {
  :one => 'There is 1 user',
  :other => 'There are %{count} users'
}
I18n.translate :user_msg, :count => 2
# => 'There are 2 users'



回答3:


I think the first part of Martin Gordon's answer is pretty good.

Alternatively, it's kind of messy but you can always just write the logic yourself:

"There #{@users.size == 1 ? 'is' : 'are'} #{@users.size} user#{'s' unless @users.size == 1}."


来源:https://stackoverflow.com/questions/8790093/how-to-pluralize-there-is-are-n-object-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!