Localization

suggest change

Localization (l10n) means making a program speak the user's language: translated text, correct plural forms, and dates and numbers written the way the user expects. Internationalization (i18n) is the groundwork that makes this possible: keeping user-visible text out of the code and looking it up by key at run time.

Ruby's standard library has no translation system. The de facto standard is the i18n gem. Rails uses it (t and l in views are thin wrappers around it), but it doesn't depend on Rails and works fine in plain Ruby scripts, command line tools and Rack or Sinatra apps.

This article covers:

The examples were run with Ruby 4.0 and i18n 1.15. Install the gem with gem install i18n (or add gem "i18n" to your Gemfile).

Translation files and lookups

Translations usually live in YAML files, one per locale. The top-level key is the locale name, and below it you can nest keys as deep as you like:

# locales/en.yml
en:
  hello: "Hello!"
  greeting: "Hello, %{name}!"
  inbox:
    title: "Inbox"
    messages:
      zero: "You have no messages"
      one: "You have 1 message"
      other: "You have %{count} messages"
  errors:
    not_found: "%{thing} not found"
# locales/de.yml
de:
  hello: "Hallo!"
  greeting: "Hallo, %{name}!"
  inbox:
    title: "Posteingang"
    messages:
      zero: "Sie haben keine Nachrichten"
      one: "Sie haben 1 Nachricht"
      other: "Sie haben %{count} Nachrichten"

Tell I18n where the files are, which locales you support, and which one is the default. Then look up text with I18n.t (short for I18n.translate):

require 'i18n'

I18n.load_path += Dir[File.join(__dir__, 'locales', '*.yml')]
I18n.available_locales = [:en, :de]
I18n.default_locale = :en

puts I18n.t(:hello)
puts I18n.t('greeting', name: 'Alice')
puts I18n.t('inbox.title')
puts I18n.t(:title, scope: :inbox)
puts I18n.t('inbox.messages', count: 0)
puts I18n.t('inbox.messages', count: 1)
puts I18n.t('inbox.messages', count: 5)

I18n.locale = :de
puts I18n.t(:hello)
puts I18n.t('greeting', name: 'Alice')
puts I18n.t('inbox.messages', count: 5)
puts I18n.t('errors.not_found', thing: 'Datei')
p I18n.locale
Hello!
Hello, Alice!
Inbox
Inbox
You have no messages
You have 1 message
You have 5 messages
Hallo!
Hallo, Alice!
Sie haben 5 Nachrichten
Translation missing: de.errors.not_found
:de

Things to note:

Besides .yml, the load path also accepts .rb files that return a Hash (useful when a value has to be a lambda) and .json files.

Lookup options: defaults, subtrees and many keys

You don't need files to try things out. store_translations adds translations from a Hash, which is also handy in tests:

require 'i18n'

I18n.available_locales = [:en, :pl]
I18n.backend.store_translations(:en, shop: {
  cart: "Cart",
  checkout: "Checkout",
  total: "Total: %{amount}",
  items: { one: "%{count} item", other: "%{count} items" }
})

p I18n.t('shop.cart')
p I18n.t('shop')                       # a whole subtree comes back as a Hash
p I18n.t([:cart, :checkout], scope: :shop) # several keys at once
p I18n.t('shop.coupon', default: 'Coupon')
p I18n.t('shop.coupon', default: [:'shop.cart', 'fallback'])
p I18n.exists?('shop.cart'), I18n.exists?('shop.coupon')
"Cart"
{cart: "Cart", checkout: "Checkout", total: "Total: %{amount}", items: {one: "%{count} item", other: "%{count} items"}}
["Cart", "Checkout"]
"Coupon"
"Cart"
true
false

default: takes a string, or a Symbol that is looked up as another key, or an Array of those that are tried in order until one is found. I18n.exists? checks for a key without producing a "missing" string.

Interpolation

%{name} in a translation is replaced by the matching keyword argument. Use %% for a literal percent sign:

require 'i18n'
I18n.available_locales = [:en]
I18n.backend.store_translations(:en, total: "Total: %{amount}", pct: "%{n}%% done, %%{literal}")

p I18n.t(:total)                 # no values given: returned as is
begin
  I18n.t(:total, price: 5)       # values given, but not the one needed
rescue I18n::MissingInterpolationArgument => e
  puts "#{e.class}: #{e.message}"
end
p I18n.t(:pct, n: 50)
p I18n.interpolate("Hi %{name}", name: "Bob")
I18n.config.missing_interpolation_argument_handler = ->(key, values, string) { "[#{key}?]" }
p I18n.t(:total, price: 5)
"Total: %{amount}"
I18n::MissingInterpolationArgument: missing interpolation argument :amount in "Total: %{amount}" ({price: 5} given)
"50% done, %{literal}"
"Hi Bob"
"Total: [amount?]"

Interpolation only happens when you pass at least one value. Without any, you get the raw string back, placeholders and all. Extra values that the string doesn't use are ignored. If you'd rather show something than crash when a translator renames a placeholder, set missing_interpolation_argument_handler.

Always give translators whole sentences with placeholders. Don't glue translated fragments together:

# Bad: word order differs between languages
I18n.t(:deleted) + " " + filename + " " + I18n.t(:from) + " " + folder

# Good: the translator controls the order
I18n.t(:file_deleted, file: filename, folder: folder)
# en: "Deleted %{file} from %{folder}"
# de: "%{file} wurde aus %{folder} gelöscht"

Pluralization

When you pass count: and the translation is a Hash, I18n picks the plural form. The built-in rule knows only English-style plurals: :one for 1, :other for everything else, plus an optional :zero key for 0.

That isn't enough for many languages. Polish, for example, has three forms for integers ("1 plik", "2 pliki", "5 plików", "22 pliki") and another one for fractions. Mix in I18n::Backend::Pluralization and give each locale a rule: a lambda that maps a number to a key. Lambdas can't be written in YAML, so the rule goes in a .rb locale file:

# locales/pl.rb
# Polish has 3 plural forms: 1 plik, 2-4 pliki, 5-21 plików, 22-24 pliki, ...
{
  pl: {
    i18n: {
      plural: {
        rule: lambda do |n|
          return :other unless n.is_a?(Integer)
          if n == 1
            :one
          elsif (2..4).cover?(n % 10) && !(12..14).cover?(n % 100)
            :few
          else
            :many
          end
        end
      }
    }
  }
}
# locales/pl.yml
pl:
  files:
    one: "%{count} plik"
    few: "%{count} pliki"
    many: "%{count} plików"
    other: "%{count} pliku"
require 'i18n'
require 'i18n/backend/pluralization'

I18n::Backend::Simple.include(I18n::Backend::Pluralization)
I18n.load_path += Dir[File.join(__dir__, 'locales', 'pl.{rb,yml}')]
I18n.available_locales = [:pl]
I18n.locale = :pl

[0, 1, 2, 4, 5, 11, 12, 21, 22, 25, 102, 1.5].each do |n|
  puts I18n.t(:files, count: n)
end
0 plików
1 plik
2 pliki
4 pliki
5 plików
11 plików
12 plików
21 plików
22 pliki
25 plików
102 pliki
1.5 pliku

The key names :zero, :one, :two, :few, :many and :other are the CLDR plural category names, so translators and translation tools recognize them. You don't have to write the rules yourself: the rails-i18n gem ships rules (and date and number formats) for more than 100 locales, and it works without Rails too. The CLDR plural rules page lists the rules for each language if you need to check one.

The current locale is per thread

I18n.locale= changes the locale only for the current thread (more precisely, the current fiber). A web server that handles requests in several threads can set a different locale for each request without them interfering:

require 'i18n'
I18n.available_locales = [:en, :de, :fr]
I18n.backend.store_translations(:en, bye: "Goodbye")
I18n.backend.store_translations(:de, bye: "Auf Wiedersehen")
I18n.backend.store_translations(:fr, bye: "Au revoir")

I18n.with_locale(:de) do
  puts I18n.t(:bye)
  I18n.with_locale(:fr) { puts I18n.t(:bye) }
  puts I18n.t(:bye)
end
puts I18n.t(:bye)
puts I18n.t(:bye, locale: :fr)

# I18n.locale is per thread/fiber: setting it in one thread doesn't leak
I18n.locale = :de
threads = [:en, :fr].map do |loc|
  Thread.new do
    puts "thread start: #{I18n.locale}"
    I18n.locale = loc
    sleep 0.01
    "#{loc}: #{I18n.t(:bye)}"
  end
end
puts threads.map(&:value)
puts "main: #{I18n.locale}"
Auf Wiedersehen
Au revoir
Auf Wiedersehen
Goodbye
Au revoir
thread start: de
thread start: de
en: Goodbye
fr: Au revoir
main: de

Prefer I18n.with_locale over setting I18n.locale directly. It restores the previous locale when the block ends, even if an exception is raised, so a locale never "sticks" to a thread from a thread pool and leaks into the next request. To translate a single string into a specific language (for example an email to another user), pass locale: to t.

Recent versions of i18n keep the configuration in fiber storage (on Ruby 3.2 and later), so new threads and fibers start with a copy of their parent's locale, as thread start: de shows. Older versions started each new thread at the default locale, so don't rely on either behaviour: set the locale explicitly inside the thread.

Missing translations

By default a missing key gives a "Translation missing: de.some.key" string, which is easy to overlook. In tests you usually want an exception instead. Use raise: true or the bang version t!. Continuing the shop example from above:

p I18n.t('shop.coupon')
begin
  I18n.t('shop.coupon', raise: true)
rescue I18n::MissingTranslationData => e
  puts "#{e.class}: #{e.message}"
end
begin
  I18n.t!('shop.coupon', locale: :pl)
rescue I18n::MissingTranslationData => e
  puts "#{e.class}: #{e.message}"
end
begin
  I18n.t('shop.cart', locale: :fr)
rescue I18n::InvalidLocale => e
  puts "#{e.class}: #{e.message}"
end
"Translation missing: en.shop.coupon"
I18n::MissingTranslationData: Translation missing: en.shop.coupon
I18n::MissingTranslationData: Translation missing: pl.shop.coupon
I18n::InvalidLocale: :fr is not a valid locale

Asking for a locale that isn't in available_locales always raises I18n::InvalidLocale. That protects you from user input like ?locale=../../etc reaching your lookups, but it also means you must validate a locale before you set it.

In production you may want to log missing keys and show something sensible to the user. I18n.exception_handler is called for every lookup failure, and whatever it returns is used as the translation:

require 'i18n'

I18n.available_locales = [:en, :de]
I18n.backend.store_translations(:en, save: "Save", cancel: "Cancel")
I18n.backend.store_translations(:de, save: "Speichern")

class CollectMissing
  attr_reader :missing

  def initialize = @missing = Set.new

  def call(exception, locale, key, options)
    if exception.is_a?(I18n::MissingTranslation)
      @missing << "#{locale}.#{key}"
      # show the English text instead of an error message
      return I18n.t(key, **options, locale: I18n.default_locale) unless locale == I18n.default_locale
      return key.to_s.split(".").last.tr("_", " ").capitalize
    end
    raise exception.respond_to?(:to_exception) ? exception.to_exception : exception
  end
end

handler = CollectMissing.new
I18n.exception_handler = handler

I18n.with_locale(:de) do
  p I18n.t(:save), I18n.t(:cancel), I18n.t(:delete_all)
end
p I18n.t(:delete_all)
p handler.missing.to_a
"Speichern"
"Cancel"
"Delete all"
"Delete all"
["de.cancel", "de.delete_all", "en.delete_all"]

In a real app you'd send missing to your log (see Logging) instead of keeping it in memory.

Fallbacks between locales

Regional variants usually differ in only a few words. Austrian German says "Jänner" for January, but everything else is the same as in German. With the Fallbacks module, a lookup that fails in de-AT is retried in de and finally in the default locale:

require 'i18n'
require 'i18n/backend/fallbacks'

I18n::Backend::Simple.include(I18n::Backend::Fallbacks)
I18n.available_locales = [:en, :de, :'de-AT', :fr]
I18n.default_locale = :en
I18n.fallbacks = I18n::Locale::Fallbacks.new(:en, fr: [:de])

I18n.backend.store_translations(:en, cart: "Cart", jan: "January", help: "Help")
I18n.backend.store_translations(:de, cart: "Warenkorb", jan: "Januar")
I18n.backend.store_translations(:'de-AT', jan: "Jänner")

p I18n.fallbacks[:'de-AT']
p I18n.fallbacks[:fr]
I18n.with_locale(:'de-AT') do
  p [I18n.t(:jan), I18n.t(:cart), I18n.t(:help)]
end
I18n.with_locale(:fr) do
  p [I18n.t(:jan), I18n.t(:cart), I18n.t(:help)]
end
[:"de-AT", :de, :en]
[:fr, :de, :en]
["Jänner", "Warenkorb", "Help"]
["Januar", "Warenkorb", "Help"]

I18n::Locale::Fallbacks.new(:en, fr: [:de]) sets :en as the last resort for every locale and adds an explicit (and here rather odd) chain for French. The region-to-language step (de-AT to de) is automatic.

Dates and times

I18n.l (short for localize) formats Date, Time and DateTime objects. It uses strftime format strings stored in the locale files, and replaces %a, %A, %b, %B, %p and %P with translated day names, month names and AM/PM markers. The i18n gem doesn't ship this data, so you have to provide it (or use rails-i18n):

# dates/de.yml
de:
  date:
    formats:
      default: "%d.%m.%Y"
      short: "%-d. %b"
      long: "%A, %-d. %B %Y"
    day_names: [Sonntag, Montag, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag]
    abbr_day_names: [So, Mo, Di, Mi, Do, Fr, Sa]
    month_names: [~, Januar, Februar, März, April, Mai, Juni, Juli, August, September, Oktober, November, Dezember]
    abbr_month_names: [~, Jan, Feb, Mär, Apr, Mai, Jun, Jul, Aug, Sep, Okt, Nov, Dez]
  time:
    formats:
      default: "%d.%m.%Y %H:%M"
      short: "%-d. %b %H:%M"
      long: "%A, %-d. %B %Y, %H:%M Uhr"
    am: vormittags
    pm: nachmittags
# dates/en.yml
en:
  date:
    formats:
      default: "%Y-%m-%d"
      short: "%b %-d"
      long: "%A, %B %-d, %Y"
    day_names: [Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday]
    abbr_day_names: [Sun, Mon, Tue, Wed, Thu, Fri, Sat]
    month_names: [~, January, February, March, April, May, June, July, August, September, October, November, December]
    abbr_month_names: [~, Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct, Nov, Dec]
  time:
    formats:
      default: "%Y-%m-%d %H:%M"
      short: "%b %-d, %-l:%M %p"
      long: "%A, %B %-d, %Y at %-l:%M %p"
    am: AM
    pm: PM

month_names starts with ~ (nil) so that January is at index 1, matching Date#month.

require 'i18n'
require 'date'

I18n.load_path += Dir[File.join(__dir__, 'dates', '*.yml')]
I18n.available_locales = [:en, :de]

date = Date.new(2026, 3, 5)
time = Time.new(2026, 3, 5, 14, 30, 0)

%i[en de].each do |loc|
  I18n.with_locale(loc) do
    puts "--- #{loc}"
    puts I18n.l(date)
    puts I18n.l(date, format: :short)
    puts I18n.l(date, format: :long)
    puts I18n.l(time)
    puts I18n.l(time, format: :long)
    puts I18n.l(time, format: "%a %d %b, %I:%M %p (%P)")
  end
end

puts time.strftime("%A, %B %e")   # strftime itself is always English
p I18n.t('date.month_names', locale: :de)[3]
begin
  I18n.l(nil)
rescue I18n::ArgumentError => e
  puts "#{e.class}: #{e.message}"
end
--- en
2026-03-05
Mar 5
Thursday, March 5, 2026
2026-03-05 14:30
Thursday, March 5, 2026 at 2:30 PM
Thu 05 Mar, 02:30 PM (pm)
--- de
05.03.2026
5. Mär
Donnerstag, 5. März 2026
05.03.2026 14:30
Donnerstag, 5. März 2026, 14:30 Uhr
Do 05 Mär, 02:30 NACHMITTAGS (nachmittags)
Thursday, March  5
"März"
I18n::ArgumentError: Object must be a Date, DateTime or Time object. nil given.

Notes:

Numbers and currency

Different countries write 1234567.891 as 1,234,567.89, 1.234.567,89, 1 234 567,89 or 1'234'567.89. The i18n gem has no number formatting (Rails gets it from ActiveSupport's number_to_currency and friends), but keeping the separators in the locale files and writing a small helper is easy:

require 'i18n'

I18n.available_locales = [:en, :de, :fr, :'de-CH']
I18n.backend.store_translations(:en, number: {
  format: { separator: ".", delimiter: ",", precision: 2 },
  currency: { format: { unit: "$", format: "%u%n" } }
})
I18n.backend.store_translations(:de, number: {
  format: { separator: ",", delimiter: ".", precision: 2 },
  currency: { format: { unit: "€", format: "%n %u" } }
})
I18n.backend.store_translations(:fr, number: {
  format: { separator: ",", delimiter: " ", precision: 2 },
  currency: { format: { unit: "€", format: "%n %u" } }
})
I18n.backend.store_translations(:'de-CH', number: {
  format: { separator: ".", delimiter: "'", precision: 2 },
  currency: { format: { unit: "CHF", format: "%u %n", negative_format: "%u-%n" } }
})

module LocalFormat
  module_function

  def number(value, precision: nil)
    fmt = I18n.t('number.format')
    precision ||= fmt[:precision]
    int, frac = format("%.#{precision}f", value).split(".")
    sign = int.delete_prefix!("-") ? "-" : ""
    int = int.reverse.scan(/\d{1,3}/).join(fmt[:delimiter]).reverse
    [sign + int, frac].compact.join(fmt[:separator])
  end

  def currency(value)
    fmt = I18n.t('number.currency.format')
    pattern = value.negative? ? fmt.fetch(:negative_format, "-#{fmt[:format]}") : fmt[:format]
    pattern.sub("%n", number(value.abs)).sub("%u", fmt[:unit])
  end
end

%i[en de fr de-CH].each do |loc|
  I18n.with_locale(loc) do
    puts format("%-6s %-14s %-14s %s", loc, LocalFormat.number(1234567.891),
                LocalFormat.currency(-1234.5), LocalFormat.number(42, precision: 0))
  end
end
en     1,234,567.89   -$1,234.50     42
de     1.234.567,89   -1.234,50 €    42
fr     1 234 567,89   -1 234,50 €    42
de-CH  1'234'567.89   CHF-1'234.50   42

The key names (number.format.separator, number.currency.format.unit and so on) are the ones Rails and rails-i18n use, so the same locale files work if you move to ActiveSupport's helpers later. Real French typography uses a narrow no-break space as the thousands delimiter. Put that character in the locale file instead of a plain space so numbers don't wrap across lines.

The currency unit is a property of the money, not of the user's locale. Show a price in euros as euros, with German or English formatting depending on who is reading it. Don't turn dollars into euros by switching the locale.

Choosing the user's locale

A web app normally gets the locale from the URL (/de/products), a user setting, or the Accept-Language request header. The header lists languages with optional quality weights, for example de-AT,de;q=0.9,en;q=0.8. Pick the best one you support and fall back to just the language part:

require 'i18n'

I18n.available_locales = [:en, :de, :'pt-BR', :pt]
I18n.default_locale = :en

# Parse "da, en-GB;q=0.8, en;q=0.7" into ["da", "en-GB", "en"], best first
def parse_accept_language(header)
  header.to_s.split(",").filter_map do |part|
    tag, *params = part.strip.split(";")
    next if tag.nil? || tag.empty? || tag == "*"
    q = params.find { _1.strip.start_with?("q=") }&.then { _1.strip[2..].to_f } || 1.0
    [tag.strip, q] if q.positive?
  end.sort_by.with_index { |(_, q), i| [-q, i] }.map(&:first)
end

def best_locale(header)
  available = I18n.available_locales.to_h { [_1.to_s.downcase, _1] }
  parse_accept_language(header).each do |tag|
    tag = tag.downcase
    return available[tag] if available[tag]          # exact: pt-br
    base = tag.split("-").first
    return available[base] if available[base]        # language only: de-at -> de
  end
  I18n.default_locale
end

[
  "de-AT,de;q=0.9,en;q=0.8",
  "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5",
  "pt-br",
  "en;q=0.5, de",
  "ja, zh;q=0.9",
  nil
].each { |h| puts "#{h.inspect.ljust(48)} => #{best_locale(h).inspect}" }

# A command line program can use the LANG environment variable instead
def locale_from_env(env = ENV)
  raw = env["LC_ALL"] || env["LC_MESSAGES"] || env["LANG"]
  tag = raw.to_s.split(".").first.to_s.tr("_", "-")   # "de_AT.UTF-8" -> "de-AT"
  best_locale(tag)
end

p locale_from_env("LANG" => "de_AT.UTF-8")
p locale_from_env("LANG" => "pt_BR.UTF-8")
p locale_from_env("LANG" => "C")
"de-AT,de;q=0.9,en;q=0.8"                        => :de
"fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5"   => :en
"pt-br"                                          => :"pt-BR"
"en;q=0.5, de"                                   => :de
"ja, zh;q=0.9"                                   => :en
nil                                              => :en
:de
:"pt-BR"
:en

sort_by.with_index keeps languages with equal weights in the order the browser sent them. Because best_locale only ever returns a value from available_locales, its result is always safe to pass to I18n.with_locale.

In a Rack app this fits naturally in a middleware (see HTTP middleware) that wraps each request in with_locale:

class SetLocale
  def initialize(app) = @app = app

  def call(env)
    locale = best_locale(env["HTTP_ACCEPT_LANGUAGE"])
    status, headers, body = I18n.with_locale(locale) { @app.call(env) }
    headers["content-language"] = locale.to_s
    headers["vary"] = [headers["vary"], "accept-language"].compact.join(", ")
    [status, headers, body]
  end
end

I18n.backend.store_translations(:en, welcome: "Welcome")
I18n.backend.store_translations(:de, welcome: "Willkommen")

app = ->(env) { [200, { "content-type" => "text/plain" }, [I18n.t(:welcome)]] }
stack = SetLocale.new(app)
p stack.call("HTTP_ACCEPT_LANGUAGE" => "de-DE,de;q=0.9")
p stack.call({})
[200, {"content-type" => "text/plain", "content-language" => "de", "vary" => "accept-language"}, ["Willkommen"]]
[200, {"content-type" => "text/plain", "content-language" => "en", "vary" => "accept-language"}, ["Welcome"]]

Vary: Accept-Language tells caches that the response depends on that header. If your app streams the body lazily (the body object renders text while the server iterates over it), that rendering happens after with_locale has returned. In that case, render eagerly or set the locale inside the body as well.

Keeping locale files in sync

Translations drift. Someone adds a key in English and forgets German, or a translator renames %{name} to %{nmae}. A short script, run in CI, catches both problems:

require 'yaml'

# Flatten {"inbox" => {"title" => "..."}} into {"inbox.title" => "..."}
def flatten_keys(hash, prefix = nil)
  hash.each_with_object({}) do |(key, value), out|
    full = [prefix, key].compact.join(".")
    if value.is_a?(Hash) && !(value.keys - %w[zero one few many other]).empty?
      out.merge!(flatten_keys(value, full))
    else
      out[full] = value
    end
  end
end

def placeholders(value) = value.to_s.scan(/%\{(\w+)\}/).flatten.sort.uniq

files = Dir[File.join(__dir__, 'locales', '*.yml')].sort
data = files.to_h do |f|
  locale, tree = YAML.load_file(f).first
  [locale, flatten_keys(tree)]
end

base = data.fetch("en")
(data.keys - ["en"]).each do |locale|
  keys = data[locale]
  missing = base.keys - keys.keys
  extra = keys.keys - base.keys
  puts "#{locale}: missing #{missing.inspect}" unless missing.empty?
  puts "#{locale}: not in en #{extra.inspect}" unless extra.empty?
  (base.keys & keys.keys).each do |k|
    next if placeholders(base[k]) == placeholders(keys[k])
    puts "#{locale}: #{k} uses #{placeholders(keys[k])}, en uses #{placeholders(base[k])}"
  end
end

Run against the English file from the start of the article and this broken German file:

de:
  hello: "Hallo!"
  greeting: "Hallo, %{nmae}!"
  inbox:
    messages:
      one: "Sie haben 1 Nachricht"
      other: "Sie haben %{count} Nachrichten"
  errors:
    not_found: "%{thing} nicht gefunden"
  goodbye: "Tschüss"
de: missing ["inbox.title"]
de: not in en ["goodbye"]
de: greeting uses ["nmae"], en uses ["name"]

A Hash whose keys are all plural categories is treated as a single translation, because languages legitimately have different sets of plural forms (German has no :few, Polish has no :zero). The i18n-tasks gem does this kind of checking, and much more, for bigger projects: it also finds keys that are used in code but missing from the files, and keys that are never used.

Sorting and case conversion

Translated strings bring non-ASCII characters, and Ruby's default string comparison sorts by codepoint, which puts all uppercase letters before lowercase ones and all accented letters after z:

words = %w[zebra Äpfel apple Österreich Ober éclair eclair Zürich]

p words.sort                      # by codepoint: uppercase, then lowercase, then accented
p words.sort_by(&:downcase)       # still puts accented letters last

# Rough language-neutral key: strip accents, ignore case
def sort_key(s)
  base = s.unicode_normalize(:nfd).gsub(/\p{Mn}/, "").downcase(:fold)
  [base, s]                       # tie-break so "eclair" and "éclair" are stable
end
p words.sort_by { sort_key(_1) }

name = "istanbul"
p name.capitalize, name.capitalize(:turkic)
p "DIŞ İŞLER".downcase, "DIŞ İŞLER".downcase(:turkic)
["Ober", "Zürich", "apple", "eclair", "zebra", "Äpfel", "Österreich", "éclair"]
["apple", "eclair", "Ober", "zebra", "Zürich", "Äpfel", "éclair", "Österreich"]
["Äpfel", "apple", "eclair", "éclair", "Ober", "Österreich", "zebra", "Zürich"]
"Istanbul"
"İstanbul"
"diş i̇şler"
"dış işler"

NFD normalization splits é into e plus a combining accent (a Unicode "nonspacing mark", \p{Mn}), and the gsub removes the marks. The result is good enough for many lists in Western European languages. It is still not truly locale-aware: in Swedish ä and ö sort after z, and in German phone books ä sorts like ae. For correct collation use ICU through a gem such as ffi-icu or twitter_cldr.

Ruby's case methods are Unicode-aware but locale-neutral. The only locale option is :turkic, for Turkish and Azerbaijani, where i/İ and ı/I are separate letters. More on encodings and normalization in Unicode and encodings and Case manipulation.

To turn localized text into ASCII, for example to build URL slugs, I18n.transliterate replaces accented Latin letters. You can add language-specific rules:

require 'i18n'
I18n.available_locales = [:en, :de]
p I18n.transliterate("Crème brûlée à Zürich")
p I18n.transliterate("Łódź 東京")
I18n.backend.store_translations(:de, i18n: { transliterate: { rule: { "ü" => "ue", "ö" => "oe", "ä" => "ae", "ß" => "ss" } } })
p I18n.transliterate("Zürich Straße", locale: :de)
"Creme brulee a Zurich"
"Lodz ??"
"Zuerich Strasse"

Characters outside the Latin alphabet become ?, so don't rely on transliteration for scripts like Japanese, Chinese or Cyrillic.

Tips

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents