Transliteration with Iconv in Ruby

前端 未结 3 943
礼貌的吻别
礼貌的吻别 2021-01-12 10:01

When I\'m trying to transliterate a Cyrillic utf-8 string with

Iconv.iconv(\'ascii//ignore//translit\', \'utf-8\', string).to_s

(see questi

相关标签:
3条回答
  • 2021-01-12 10:37
    require 'iconv'
    p Iconv.iconv('ascii//translit//ignore', 'utf-8',  'Gévry') #=> ["Gevry"]
    # not         'ascii//ignore//translit'
    

    For Cyrillic the translit gem might work.

    0 讨论(0)
  • 2021-01-12 10:45

    It seems the solution is too tricky for me. Problem solved using stringex gem.

    0 讨论(0)
  • 2021-01-12 10:48

    Another way is to create custom translit by tr and gsub methods of String without using iconv.

    # encoding: UTF-8
    
    def russian_translit(text)
        translited = text.tr('абвгдеёзийклмнопрстуфхэыь', 'abvgdeezijklmnoprstufhey\'')
        translited = translited.tr('АБВГДЕЁЗИЙКЛМНОПРСТУФХЭ', 'ABVGDEEZIJKLMNOPRSTUFHEY\'')
    
        translited = translited.gsub(/[жцчшщъюяЖЦЧШЩЪЮЯ]/,
            'ж' => 'zh', 'ц' => 'ts', 'ч' => 'ch', 'ш' => 'sh', 'щ' => 'sch', 'ъ' => '', 'ю' => 'ju', 'я' => 'ja',
            'Ж' => 'ZH', 'Ц' => 'TS', 'Ч' => 'CH', 'Ш' => 'SH', 'Щ' => 'SCH', 'Ъ' => '', 'Ю' => 'JU', 'Я' => 'JA')
        return translited
    end
    
    p russian_translit("В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!")
    #=> "V chaschah juga zhil by tsitrus? Da, no fal'shivyj ekzempljar!"
    
    0 讨论(0)
提交回复
热议问题