Search code examples
rubytextunicodecjk

Convert full-width Japanese text to half-width (zen-kaku to han-kaku)


In PHP it's possible to convert double-width characters to single width with the function mb_convert_kana. They call it "convert zen-kaku to han-kaku".

For example, I have a string to convert:

dbl = "BOX"

and I'd like to find some method like this

dbl = "BOX".convert_to_half_width # dbl is now "BOX"

Is there a way to do this in Ruby?


Solution

  • I use a combination of the Ruby built-in NKF and String#tr

    require 'nkf'
    dbl = "BOXカタカナ"
    dbl = NKF.nkf('-X -w', dbl).tr('0-9a-zA-Z', '0-9a-zA-Z')
    # dbl now is "BOXカタカナ"
    

    This has the added benefit of transposing half-width katakana to full-with katakana as well.