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

Labels: ,




Comments:
"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".
 
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.
 
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
 
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.
 
Hi Jay, I think there's a copy/paste bug in the name of the test.

-Alistair
 
Thanks Alistair, it should be fixed now.
 
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...
 
Post a Comment

<< Home

This page is powered by Blogger. Isn't yours?