测试 Ruby on Rails 中的单词是单数还是复数
快问。
如何测试一个单词是单数还是复数?
我真的很喜欢:
test_singularity('word') # => true
test_singularity('words') # => false
我打赌 Rails 是有能力的!
谢谢。
Quick question.
How can I test a word to see if it is singular or plural?
I'd really like:
test_singularity('word') # => true
test_singularity('words') # => false
I bet rails is capable!
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 Rails 中,您可以进行 string#singularize|#pluralize 比较来返回 true 或 false 值。
但我认为由于语言本身的性质,这可能需要一些备份才能完全准确。
你可以这样做,
但是为了看看有多准确,我快速输入了一组单词。
事实上,我有点惊讶,因为“dress”确实得到了正确的复数,但是当它通过#singularize时,它遇到了一些障碍。
Well in rails, you can do a
string#singularize|#pluralize
comparison to return a true or false value.But I would think due to the nature of language itself, this might need some backup to do be completely accurate.
You could do something like this
But to see how accurate, I ran a quick set of words.
I was a little surprised actually, since 'dress' does get pluralized properly, but when it goes through the #singularize it runs into a bit of a snag.
大多数时候我从不测试单数或复数,我只是将其转换为我需要的单数或复数形式。
在 Rails 2.3.x 中,这是可能的,编写类似这样的内容
进一步研究此问题,很容易提供工作函数:
它给出以下输出:
在 Rails 4 中,有了给定的话,现在就容易多了。你可以这样做
,因此该功能也变得更加容易:
Most of the times i never test for singularity or plural, i just convert it to the singular or plural form i require.
In Rails 2.3.x this was possible, writing something like this
Working further on this, a working function is easy to supply:
which gives the following output:
In Rails 4, with the given words, it is now much easier. You can just do
and thus the function becomes much easier as well:
ruby 和 Rails 都没有提供测试单词“复数性”的特定方法。
正如 nowk 所说,与
word.pluralize
和word.singularize
相比,您最多可以自己实现它们。这将为您提供一种快速、廉价且总体上良好的测试方法。但有时它会失败。如果您需要更高的精度,则需要使用 Ruby Linguistics gem,它可以处理搭配衣服,衣服得体(但比较重)。
Neither ruby nor rails come with a specific method for testing for "plurality" on words.
As nowk said, the most you can do is implement them yourself, comparing with
word.pluralize
andword.singularize
. This will give you a quick-and-cheap-and-generally-good way of testing. It will fail some times, though.If you need more precision, you will need to use the Ruby Linguistics gem, which can deal with dress and dresses properly (but it's heavier).