Module: NumeralsJp::IntegerConverter

Includes:
Constant
Defined in:
lib/numerals_jp/integer_converter.rb

Overview

Represents conversions from Integer.

Constant Summary

Constants included from Constant

Constant::LARGE_FACTORS, Constant::NUMERALS, Constant::SMALL_FACTORS

Class Method Summary collapse

Class Method Details

.split_digits(i, limit) ⇒ Array<Integer>

Splits the given integer into specified digits from lower digits.

Examples:

split each digit

split_digits(1234, 1) # => [4, 3, 2, 1]

split 4 digits each

split_digits(1234567, 4) # => [4567, 123]

Parameters:

  • i (Integer)

    the integer to split

  • limit (Integer)

    the number of digits to split each

Returns:

  • (Array<Integer>)

    an Array of split integers



46
47
48
49
50
51
52
53
# File 'lib/numerals_jp/integer_converter.rb', line 46

def split_digits(i, limit)
  [].tap do |arr|
    while i > 0
      arr << i % 10 ** limit
      i /= 10 ** limit
    end
  end
end

.to_jp(i) ⇒ String

Converts positive integer which is less than 10^16 to Japanese numerals.

Examples:

to_jp(106) # => "百六"

Parameters:

  • i (Integer)

    the integer to convert

Returns:

  • (String)

    the converted string

Raises:

  • (ArgumentError)

    if the integer is not positive or less than 10^16



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/numerals_jp/integer_converter.rb', line 15

def to_jp(i)
  raise ArgumentError.new("the integer out of range") unless i > 0 && i < 10 ** 16

  if i < 10000
    split_digits(i, 1)
      .zip([nil] + SMALL_FACTORS.keys)
      .reject { |num, factor| num == 0 }
      .map { |num, factor| "#{num if num != 1 || factor.nil?}#{factor}" }
      .reverse
      .join
      .tr("1-9", NUMERALS)
  else
    split_digits(i, 4)
      .zip([nil] + LARGE_FACTORS.keys)
      .reject { |num, factor| num == 0 }
      .map { |num, factor| "#{num.to_jp}#{factor}" }
      .reverse
      .join
  end
end