ruby – How to convert full-width alphanumericals and blank characters to half-width

Question: Question:

I wanted to convert full-width alphanumericals and full-width spaces to half-width characters. I tried using Moji .

We couldn't find a suitable character classification to accommodate double-byte spaces.

Regarding full-width alphanumerical characters

Moji.zen_to_han(str, Moji.ALNUM)

The conversion is as expected. Moji.SYMBOL ,are half-width.

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?

Answer: Answer:

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)"0-9A-Za-z ", "0-9A-Za-z ")

class ZenToHanTest < Minitest::Test
  def test_zen_to_han
    assert_equal "ABCabc 123", zen_to_han("ABCabc 123")
    assert_equal "あいうえお123-456", zen_to_han("あいうえお123-456")

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.

Scroll to Top