Is there a pluralize function in Ruby NOT Rails?

Solution 1:

Actually all you need to do is

require 'active_support/inflector'

and that will extend the String type.

you can then do

"MyString".pluralize

which will return

"MyStrings"

for 2.3.5 try:

require 'rubygems'
require 'active_support/inflector'

should get it, if not try

sudo gem install activesupport

and then the requires.

Solution 2:

Inflector is overkill for most situations.

def x(n, singular, plural=nil)
    if n == 1
        "1 #{singular}"
    elsif plural
        "#{n} #{plural}"
    else
        "#{n} #{singular}s"
    end
end

Put this in common.rb, or wherever you like your general utility functions and...

require "common" 

puts x(0, 'result') # 0 results
puts x(1, 'result') # 1 result
puts x(2, 'result') # 2 results

puts x(0, 'match', 'matches') # 0 matches
puts x(1, 'match', 'matches') # 1 match 
puts x(2, 'match', 'matches') # 2 matches 

Solution 3:

I personally like the linguistics gem that is definitely not rails related.

# from it's frontpage
require 'linguistics'

Linguistics.use :en

"box".en.plural #=> "boxes"
"mouse".en.plural #=> "mice"
# etc

Solution 4:

This works for me (using ruby 2.1.1 and actionpack 3.2.17):

~$ irb
>> require 'action_view'
=> true
>> include ActionView::Helpers::TextHelper
=> Object
>> pluralize(1, 'cat')
=> "1 cat"
>> pluralize(2, 'cat')
=> "2 cats"