I wanted to convert full-width alphanumericals and full-width spaces to half-width characters. I tried using
We couldn't find a suitable character classification to accommodate double-byte spaces.
Regarding full-width alphanumerical characters
The conversion is as expected.
Moji.zen_to_han(str, Moji.ALNUM).gsub(" "," ")
I am converting a full-width space to a half-width space, but I feel that it is troublesome twice even though I am using Gem for full-width half-width conversion.
Is there a better way to deal with it?
It's convenient to use a library, but it can get tedious as soon as you try to control small movements.
(When using Rails, if you don't get on the "rail" properly, the implementation will be complicated.)
As for the question, "I want to convert only full-width alphanumericals and full-width spaces to half-width" is a little special as a use case, so it seems a bit strict to ask the library to do something about it.
This page showed how to change it only with Ruby without using his Moji.
If you refer to this, you can implement it like this.
require 'minitest/autorun' def zen_to_han(str) str.tr("０-９Ａ-Ｚａ-ｚ ", "0-9A-Za-z ") end class ZenToHanTest < Minitest::Test def test_zen_to_han assert_equal "ABCabc 123", zen_to_han("ＡＢＣａｂｃ １２３") assert_equal "あいうえお123－456", zen_to_han("あいうえお１２３－４５６") end end
With this, you can control the rules for full-width and half-width conversion relatively freely.
It may be subtle whether it is simpler than
Moji.zen_to_han(str, Moji.ALNUM).gsub(" "," ") , but I think it has the advantage of increasing the degree of freedom of conversion.