Sunday, November 04, 2007

Rails: String#pluralize

Documentation
Returns the plural form of the word in the string.

Examples
  • "post".pluralize #=> "posts"
  • "octopus".pluralize #=> "octopi"
  • "sheep".pluralize #=> "sheep"
  • "words".pluralize #=> "words"
  • "the blue mailman".pluralize #=> "the blue mailmen"
  • "CamelOctopus".pluralize #=> "CamelOctopi"
Usage
I generally use pluralize for creating nice messages for users. The pluralize method can also be helpful for metaprogramming when converting from a class name to a table name.

Test

require 'rubygems'
require 'active_support'
require 'test/unit'
require 'dust'

unit_tests do
test "change singular word to plural word" do
assert_equal "names", "name".pluralize
end
end

8 comments:

  1. "CamelOctopus".pluralize #=> "CamelOctopi"

    Ugh ... it frustrates me that Rails codifies a grammatical error.

    The plural of "octopus" is "octopodes" -- or "octopuses" if you wish to Anglicize it -- not "octopi".

    Even though the word ends in -us, "pus" is a Greek root and not a Latin one, meaning "foot" -- witness "pedestrian" or "pedal".

    ReplyDelete
  2. And it also chokes on another common construct:

    "attorney general".pluralize #=> "attorney generals"

    It's actually "attorneys general".

    That one is more easily understood -- it would be non-trivial to identify "attorney general" as a noun-adjective construct.

    But actually specifying something incorrect, like "octopi"? Blech.

    ReplyDelete
  3. Not a problem, Joe. active_support lets one customize pluralization rules.


    Inflector.inflections do |inflect|
    inflect.irregular 'octopus', 'octopodes'
    inflect.irregular 'attorney general', 'attorneys general'
    end

    ReplyDelete
  4. Brian:

    Yeah, but the problem is that RoR ships with an error. The octopus/octopi thing appears six times in lib/active_support/inflector.rb as an example of the "right" way to do pluralization/singularization. :(

    A nitpick, I know.

    ReplyDelete
  5. Hi Jay, I think there's a copy/paste bug in the name of the test.

    -Alistair

    ReplyDelete
  6. Thanks Alistair, it should be fixed now.

    ReplyDelete
  7. http://www.reference.com/search?r=13&q=Octopodes

    according to reference.com 3 forms are right : octopus = 'eight-legs', with plural forms: octopuses, octopi, or octopodes and reference.com uses octopuses as plural form in text.

    just noticed...

    ReplyDelete
  8. Chris Peters7:36 AM

    What's the problem? Rails is open source. Stop whining, fix it, and submit a pull request.

    ReplyDelete

Note: Only a member of this blog may post a comment.