LoginSignup
8

More than 5 years have passed since last update.

posted at

updated at

色んな表記ゆれを無視して比較する (String拡張)

# [Example]
#   "one two three 4 5 ".eql? "ONE TWO three 4 五  \t"
#      # => false
#   "one two three 4 5 ".neql? "ONE TWO three 4 五  \t"
#      # => true
#   "ONE TWO three 4 五  \t".flattening
#      # => "ONE TWO THREE 4 5 "

# Mojiモジュールが必要。作成者である「Gimite 市川」様に感謝!
# (公式HP) http://gimite.net/gimite/rubymess/moji.html
require "moji"
# ZenToIモジュールが必要。作成者である「yoshitsugu」様に感謝!
# (公式HP)  https://github.com/yoshitsugu/zen_to_i
require "zen_to_i"

class String

  # 表記ゆれを無視した上で、文字列の比較を行う
  def nearly_equal?(other_str)
    self.flattening == other_str.flattening
  end
  alias_method :neql?, :nearly_equal?

  # 表記ゆれをなくした文字列を返す
  def flattening
    target = self
    # 全角大文字英字, 全角小文字英字, 半角小文字英字 -> 半角大文字英字
    # 全角数字 -> 半角数字
    target = Moji.zen_to_han(target, Moji::ZEN_ALNUM).upcase
    # 半角カタカナ -> 全角カタカナ
    target = Moji.han_to_zen(target, Moji::HAN_KATA)
    # 全角スペース,タブ -> 半角スペース
    target.gsub!(/[\s ]+/, ' ')
    # 漢数字 -> 半角数字
    target.zen_to_i
  end

  # 表記ゆれをなくし(破壊的変更)、かつ、文字列を返す
  def flattening!
    self.replace(self.flattening)
  end
end

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
8