views:

710

answers:

4

Writing some ruby code (not rails) and I need to handle something like this:

found 1 match
found 2 matches

I have rails installed so maybe I might be able to add a require clause at the top of the script, but does anyone know of a RUBY method that pluralizes strings? Is there a class I can require that can deal with this if the script isn't rails but I have rails installed?

Thanks in advance!

Edit: All of these answers were close but I checked off the one that got it working for me. Try this method as a helper when writing ruby (not rails) code:

def pluralize(number, text)
  return text.pluralize if number != 1
  text
end

Hope that helps!

A: 
require 'active_support'
require 'active_support/inflector'

inf = ActiveSupport::Inflector::Inflections.new

to get the inflector, not sure how you use it

scaney
+7  A: 

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"
scaney
Ok, this isn't working. I'm getting "LoadError: no such file to load -- active_support/inflector" Are you forgetting anything? when listing gems I have activesupport 2.3.5
DJTripleThreat
for 2.3.5 sudo gem install activesupport require 'rubygems' require 'active_support/inflector'should get itI'm using edge rails (3) there's been a lot of decoupling, and it appears to bundle with it by default
scaney
+3  A: 

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.

scaney
that did it! thanks!!
DJTripleThreat
+2  A: 

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, 'tree') # 0 trees
puts x(1, 'tree') # 1 tree
puts x(2, 'tree') # 2 trees

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