module YaKansuji

Yet another Kansuji library for ruby.

String and Integer refinements with YaKansuji

Simple kansuji formatter

Simple kansuji formatter

Simple kansuji formatter

Simple kansuji formatter

Simple kansuji formatter

Constants

NUM_ALT_CHARS
NUM_NORMALIZED_CHARS
REGEXP
REGEXP_PART
UNIT_EXP3
UNIT_EXP4
VERSION

Public Instance Methods

formatter(sym) click to toggle source
# File lib/ya_kansuji.rb, line 91
def formatter(sym)
  @@formatters[sym]
end
formatters() click to toggle source
# File lib/ya_kansuji.rb, line 95
def formatters
  @@formatters
end
register_formatter(sym, proc = nil, &block) click to toggle source
# File lib/ya_kansuji.rb, line 81
def register_formatter(sym, proc = nil, &block)
  if block_given?
    @@formatters[sym] = block
  elsif proc.respond_to? :call
    @@formatters[sym] = proc
  else
    raise ArgumentError, 'Registering invalid formatter.'
  end
end
to_i(str) click to toggle source
# File lib/ya_kansuji.rb, line 25
def to_i(str)
  str = str.to_s.tr(NUM_ALT_CHARS, NUM_NORMALIZED_CHARS)
  str.gsub!(/[,,、:space:]/, '')
  matched = REGEXP.match(str) or return 0
  ret3 = 0
  ret4 = 0
  curnum = nil
  if str.respond_to? :_to_i_ya_kansuji_orig
    to_i_meth = :_to_i_ya_kansuji_orig
  else
    to_i_meth = :to_i
  end
  matched[0].scan(REGEXP_PART).each do |c|
    case c
    when '1', '2', '3', '4', '5', '6', '7', '8', '9'
      if curnum
        curnum *= 10
      else
        curnum = 0
      end
      curnum += c.public_send(to_i_meth)
    when '0'
      curnum and curnum *= 10
    when '卄', '廿'
      ret3 += 20
      curnum = nil
    when '卅', '丗'
      ret3 += 30
      curnum = nil
    when '卌'
      ret3 += 40
      curnum = nil
    when '皕'
      ret3 += 200
      curnum = nil
    when *UNIT_EXP4
      if curnum
        ret3 += curnum
        curnum = nil
      end
      ret3 = 1 if ret3.zero?
      ret4 += ret3 * 10**((UNIT_EXP4.index(c) + 1) * 4)
      ret3 = 0
    when *UNIT_EXP3
      curnum ||= 1
      ret3 += curnum * 10**(UNIT_EXP3.index(c) + 1)
      curnum = nil
    end
  end
  if curnum
    ret3 += curnum
    curnum = nil
  end
  ret4 + ret3
end
to_kan(num, formatter = :simple, options = {}) click to toggle source
# File lib/ya_kansuji.rb, line 99
def to_kan(num, formatter = :simple, options = {})
  num.respond_to?(:_to_i_ya_kansuji_orig) ? num = num._to_i_ya_kansuji_orig : num = num.to_i
  if formatter.respond_to? :call
    formatter.call num, options
  elsif @@formatters[formatter]
    @@formatters[formatter].call num, options
  else
    raise ArgumentError, "Unable to find formatter #{formatter}"
  end
end