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.

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Got something to say?