Skip to content

How to automatically pluralize text in Ruby on Rails

Posted on 09 November 2006

To automatically pluralize a word in Ruby on Rails you just need to do the following:

<%= pluralize(messages.length, "new message") %>

So you just pass the method a number and the singular word or phrase. Rails will try to pluralize it unless the number is 1.

Rails uses the following 'inflections' by default:

# Add new inflection rules using the following format 
# (all these examples are active by default):
# Inflector.inflections do |inflect|
#   inflect.plural /^(ox)$/i, '\1en'
#   inflect.singular /^(ox)en/i, '\1'
#   inflect.irregular 'person', 'people'
#   inflect.uncountable %w( fish sheep )
# end

You will find these in your environment.rb file inside the config folder. If you uncomment these lines then you can create your own custom inflections. Note that any changes made in there will require you to restart your server.

View the snippets archive ››

No comments have been left

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com