Monday, November 05, 2007

Rails: String#singularize

Documentation
The reverse of pluralize, returns the singular form of a word in a string.

Examples
  • "posts".singularize #=> "post"
  • "octopi".singularize #=> "octopus"
  • "sheep".singluarize #=> "sheep"
  • "word".singluarize #=> "word"
  • "the blue mailmen".singularize #=> "the blue mailman"
  • "CamelOctopi".singularize #=> "CamelOctopus"
Usage
I generally use singularize when metaprogrammming to convert from a potentially plural version of a class name to something that I know can be constantized.

Test

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

unit_tests do
test "change plural word to singular word" do
assert_equal "class_name", "class_names".singularize
end
end

2 comments:

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