2

In Ruby on Rails, this is plural and singular functions added to Ruby string class.

How can I implements plural and singular functions in Java?

Example:

"book"  plural() => "books"
"books"  singular  =>  "book"
Lii
  • 11,553
  • 8
  • 64
  • 88
wangxl
  • 161
  • 1
  • 1
  • 5
  • This is a dupe of an earlier question... that I'm having trouble finding. It was about 2 weeks ago. If you find the question, you'll also have the answer! :) – Carl Smotricz Jul 21 '10 at 08:49
  • I'm adding this as a comment rather than an answer, because I've never tried to do anything like this, but Rails runs under JRuby, and you can compile JRuby into .class files, so what if you compiled the Rails Inflector class (or as much of ActiveSupport as necessary) into Java, then just included it from the Java? – Joshua Cheek Jul 21 '10 at 09:12
  • @Carl - [this is the earlier question](http://stackoverflow.com/questions/3189432/effective-way-to-handle-singular-plural-word-based-on-some-collection-size), but it's not a duplicate, that one asked for a solution in Java only (Carl, you even commented the best answer given there ;) ) – Andreas Dolk Jul 21 '10 at 09:15
  • @Andreas_D: That's why I remembered it. But... this question is asking about Java (only) too, isn't it? So technically a dupe, though I wouldn't fault the poster for it. Or am I all mixed up? – Carl Smotricz Jul 21 '10 at 09:31
  • @Carl - oh yes, ruby is only mentioned in the first line. As a reference... It is a duplicate. – Andreas Dolk Jul 21 '10 at 09:54

1 Answers1

5

Assuming you want to cover the exception cases too (e.g. person => people) then the module that handles this in Ruby on Rails is called Inflector. Take a look at this Inflector project on java.net for something similar in Java. From the project summary:

Inflector is a Java API for forming plurals of words. The library supports English spellings, and is locale-aware so it is straightforward to customize for any language.

Note: that I think this might only do singular => plural and not the other way around.

mikej
  • 65,295
  • 17
  • 152
  • 131
  • If I remember correctly, that was the best answer given to the previous question I mentioned. +1. :) – Carl Smotricz Jul 21 '10 at 08:52
  • Thank you It is very nice of you I get another method the url is http://www.oschina.net/bbs/thread/104 be concerned with the code only i hope you can understand Chinese haha – wangxl Jul 21 '10 at 09:59