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.

Got something to say?