【问题标题】:Rails - How to pluralize a sentence? [duplicate]Rails - 如何复数一个句子? [复制]
【发布时间】:2014-09-23 17:44:21
【问题描述】:

我知道您可以使用复数功能在 Rails 中将单词复数。

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

但我想做的是复数一个需要复数多个单词的句子。

There are <%= Cat.count %> cats

问题在于,如果只有 1 只猫。它会返回

There are 1 cats

这在语法上没有意义。

应该说

There are x cats (if x is not 1)

There is 1 cat (if there is only 1)

问题是,我不知道如何复数,因为这里有两个参数(is 和 cat)。

任何帮助将不胜感激。

也许是这样的?

if Cat.count == 1
  puts "There is 1 cat"
else
  puts "There are #{Cat.count} cats"
end

【问题讨论】:

  • 一个简单的if-else 语句就可以解决问题。
  • 写一个方法来解析你的句子并做正确的事,如果你需要它是通用的,或者基于计数构建句子。
  • 有问题的值是Cat.count 还是cat.count?哪个?
  • 我认为这个问题在这里解决得更好:stackoverflow.com/questions/1686226

标签: ruby-on-rails ruby pluralize


【解决方案1】:

您可以通过定义翻译键的计数值(即config/locales/en.yml)来使用I18n 库的pluralization features

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

然后,在您的代码中(或视图,或其他任何地方,因为I18n 是全球可用的)

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

会输出

There are 0 cats.
There is one cat.
There are 2 cats.

【讨论】:

  • 1 的输出应该是“有一只猫。”,对吧?
  • 你说得对,很好!
猜你喜欢
  • 2019-05-01
  • 2023-04-03
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 1970-01-01
  • 2016-02-09
  • 1970-01-01
相关资源
最近更新 更多