Skip to content

Instantly share code, notes, and snippets.

@nicolasblanco
Created October 7, 2010 14:30
Show Gist options
  • Save nicolasblanco/615174 to your computer and use it in GitHub Desktop.
Save nicolasblanco/615174 to your computer and use it in GitHub Desktop.
# Pluralize helper for French language.
#
# Because French pluralization has special rules :
# Example :
# pluralize(0, "degré") # => "0 degré"
# pluralize(1, "degré") # => "1 degré"
# pluralize(2, "degré") # => "2 degrés"
# pluralize(0.5, "degré") # => "0.5 degré"
# pluralize(1.9, "degré") # => "1.9 degré"
# pluralize(-1.9, "degré") # => "-1.9 degré"
# pluralize(-2, "degré") # => "-2 degrés"
#
# Options :
# :without_count : if you don't want to output the count (only the word),
# :plural : to use a custom plural.
#
def pluralize(count, singular, options = {})
"".tap do |result|
result << "#{count || 0} " unless options[:without_count]
result << (count.to_i > -2 && count.to_i < 2 ? singular : (options[:plural] || singular.pluralize)).to_s
end
end
@cyrille
Copy link

cyrille commented Oct 8, 2010

cool !

@afranke
Copy link

afranke commented Nov 7, 2010

Wouldn't gettext be able to handle this?

@nicolasblanco
Copy link
Author

afranke ? Why do you want to use gettext ? Rails already got a full internationalization system (Rails i18n API) since Rails 2.3, see : http://guides.rubyonrails.org/i18n.html to learn how to use it.

@afranke
Copy link

afranke commented Nov 7, 2010

Doesn't this i18n API already handle pluralization? I don't use Ruby nor Rails, but in other languages gettext is the de facto standard and it takes care of plurals. So I find it weird that you might need such a code and that it's not already done in the API.

@nicolasblanco
Copy link
Author

The Rails i18n system provides a lot of features to translate strings, interpolation, date/time localizing... And of course, know how to pluralize words.
This helper does not implement "singular" or "pluralize" which are already implemented in Rails i18n.
This is just an additionnal language RULE.
In English we say "0 + plural", in other language it may be different. In french we say "0 + singular". This helper is to override this rule for the French language.

@afranke
Copy link

afranke commented Nov 8, 2010

Ok, nevermind then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment