Smart Pluralize for Rails

May 19, 2009

You may know that the ActiveSupport library included with Rails contains a pluralize method that lets you pluralize a string.

For example:

$ irb
>> require "rubygems" 
=> true
>> require "activesupport" 
=> true
>> "monkey".pluralize
=> "monkeys" 
>> "ox".pluralize
=> "oxen" 

Sometimes you want to decide whether or not to pluralize a string based on a quantity. For example, at the bottom of this article should it say 1 comment or 2 comments? It depends on how many comments we have. I was running into this in a lot while pair programming on one project, so Ian Smith-Heisters and I whipped up this simple helper which makes it easy.

class String
  def smart_pluralize(num=self)
    num.to_i.abs == 1 ? self : pluralize
  end
end

Now here’s the fun part. Having this method take self (the string its called on) as its default argument is what makes this so easy to work with. You can pass a quantity explicitly to it, or just call it on a string that starts with a number.

>> "1 monkey".smart_pluralize
=> "1 monkey" 
>> "2 monkey".smart_pluralize
=> "2 monkeys" 
>> (-2..2).each do |number|
?>   puts "#{number} monkey".smart_pluralize(number).inspect
>> end
"-2 monkeys" 
"-1 monkey" 
"0 monkeys" 
"1 monkey" 
"2 monkeys" 

Here’s a link to the gist.