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

In PHP, you can convert characters of double width to one width using a 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 would like to find a method like this

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

Is there any way to do this in Ruby?

+5
source share
5 answers

The hz_on_fly gem makes replacements in the AR model, which is probably not what you want. Take a look at unicode_japanese . Just do:

Unicode::Japanese.z2h("BOX")
  # => "BOX"

My version of the project has been updated for Ruby 1.9.2 (no other AFAIKs). To use it, add this to your Gemfile:

gem 'unicode_japanese',
  :git => 'git://github.com/jpgeek/unicode_japanese.git'
0
source

Ruby NKF String#tr

require 'nkf'
dbl = "BOX"
dbl = NKF.nkf('-X -w', dbl).tr('0-9a-zA-Z', '0-9a-zA-Z')

, , katakana .

+3

There is a stone there: hz_on_fly

0
source

Well, this is ugly, and it only works for Romagi (can be expanded to deal with other characters), but it worked for me:

title = "BOX"
englishReplacements = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"
japaneseReplacements = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890"

converted = title.tr(japaneseReplacements, englishReplacements) 
# title is now "BOX"
0
source

I think Moji gem ( Japanese documentation ) would be good for this, and would also be a very useful Japanese stone in general (works with Ruby 1.8 and 1.9):

require 'moji'

dbl = Moji.zen_to_han("BOX")
# => "BOX"
0
source

All Articles