2010/03/04
I searched the Internet in vain for examples of using the Ruby i18n gem outside of Rails apps.
Below is a minimal example: the aim is (as usual) to produce a greeting - this time in English and Italian.
Installation
$ irb
>> require 'rubygems'
=> true
>> require 'sun_times'
=> true
>> SunTimes.set( Date.today, 44, 11 ).localtime
=> Tue Mar 09 18:14:08 +0100 2010
The t
method
The most common use of i18n is via I18n.translate
which has an abbreviated alias I18n.t
.
Translations
en.yml:
en:
hello world: Hello World!
it.yml:
it:
hello world: Ciao Mondo!
These translations can be accessed as follows:
I18n.t('hello world')
That will use the current locale setting. You can change it as follows:
I18n.locale = :it
The Program
After loading the i18n
gem, set up I18n.load_path
before attempting to retrieve any translations.
require 'rubygems' if RUBY_VERSION < '1.9'
require 'i18n'
I18n.load_path = ['en.yml', 'it.yml']
puts 'In English...'
I18n.locale = :en
puts I18n.t('hello world')
puts 'In Italian...'
I18n.locale = :it
puts I18n.t('hello world')
The result:
$ ruby salutation.rb
In English...
Hello World!
In Italian...
Ciao Mondo!