Ruby 中没有复数函数吗?Rails 中没有吗?
我正在编写一些 Ruby 代码,而不是 Rails,我需要处理这样的事情:
found 1 match
found 2 matches
我安装了 Rails,所以也许我可以在脚本顶部添加一个 require
子句,但确实如此有人知道可以复数字符串的 RUBY 方法吗?如果脚本不是 Rails 但我安装了 Rails,是否有一个我可以要求的类可以处理这个问题?
编辑:所有这些答案都很接近,但我勾选了对我有用的答案。 在编写 Ruby(而不是 Rails)代码时尝试使用此方法作为帮助器:
def pluralize(number, text)
return text.pluralize if number != 1
text
end
I am writing some Ruby code, not Rails, and I need to handle something like this:
found 1 match
found 2 matches
I have Rails installed so maybe I might be able to add a require
clause at the top of the script, but does anyone know of a RUBY method that pluralizes strings? Is there a class I can require that can deal with this if the script isn't Rails but I have Rails installed?
Edit: All of these answers were close but I checked off the one that got it working for me.
Try this method as a helper when writing Ruby, not Rails, code:
def pluralize(number, text)
return text.pluralize if number != 1
text
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
实际上,您需要做的就是
扩展 String 类型。
然后你可以执行
以下操作,这将返回
2.3.5 try:
应该得到它,如果没有尝试
,则需要。
Actually all you need to do is
and that will extend the String type.
you can then do
which will return
for 2.3.5 try:
should get it, if not try
and then the requires.
Inflector 在大多数情况下都太过分了。
把它放在 common.rb 中,或者任何你喜欢通用实用函数的地方......
Inflector is overkill for most situations.
Put this in common.rb, or wherever you like your general utility functions and...
我个人喜欢绝对与 Rails 无关的 语言学宝石。
I personally like the linguistics gem that is definitely not rails related.
这对我有用(使用 ruby 2.1.1 和 actionpack 3.2.17):
This works for me (using ruby 2.1.1 and actionpack 3.2.17):
得到偏转器,不知道你如何使用它
to get the inflector, not sure how you use it
我的解决方案:
因此,如果您调用 cpluralize(1, 'reviews') ,您可以返回“评论”
希望有所帮助。
my solution:
So you can have 'review' returned if you call cpluralize(1, 'reviews')
Hope that helps.
我为此定义了一个辅助函数,我将它用于每个用户可编辑模型的索引视图:
然后您可以从视图中调用它:
对于国际化(i18n),您可以将其添加到您的语言环境 YAML 文件中:
I've defined a helper function for that, I use it for every user editable model's index view :
then you can call it from the view :
for internationalization (i18n), you may then add this to your locale YAML files :