Ordinalization

Ordinalization is the process of converting a number into its ordinal form, which indicates position in a series (e.g., 1 becomes "1st", 2 becomes "2nd").

Rails provides the ActiveSupport::Inflector.ordinalize method for this purpose. While its default behavior is tailored for English, rails-i18n extends this functionality by providing custom ordinalization rules for many other languages.

How to Use

Once the gem is installed, you can use the ordinalize method, and it will automatically apply the correct rule based on the current I18n.locale.

# Default English behavior
I18n.with_locale(:en) { 1.ordinalize } # => "1st"

# French behavior provided by rails-i18n
I18n.with_locale(:fr) { 1.ordinalize } # => "1er"
I18n.with_locale(:fr) { 2.ordinalize } # => "2e"

# Danish behavior provided by rails-i18n
I18n.with_locale(:da) { 3.ordinalize } # => "3."

Implementation

The rules are defined in the rails/ordinals/ directory. Most languages use a simple rule where a period is appended to the number.

More complex languages, like French, require programmatic logic and are defined in .rb files:

Example: rails/ordinals/fr-CA.rb

{
  "fr-CA": {
    number: {
      nth: {
        ordinals: -> (_key, number:, **_options) {
          if number.to_i.abs == 1
            'er'
          else
            'e'
          end
        },

        ordinalized:  -> (_key, number:, **_options) {
          "#{number}#{ActiveSupport::Inflector.ordinal(number)}"
        }
      }
    }
  }
}

This lambda-based rule correctly applies "er" for 1 and "e" for all other numbers.

Supported Languages

Custom ordinalization rules are provided for:

be, bs, cs, da, de, de-AT, de-CH, de-DE, eo, et, fa, fi, fr, fr-CA, fr-CH, fr-FR, gd, hr, hu, is, ka, lb, lt, lv, mk, nb, ne, nn, pl, sk, sl, sq, sr, sw, tr.