Module: MoreMath::NumberifyStringFunction

Included in:
StringNumeral
Defined in:
lib/more_math/numberify_string_function.rb

Constant Summary collapse

Functions =
MoreMath::Functions

Class Method Summary collapse

Class Method Details

.convert_alphabet(alphabet) ⇒ Object



52
53
54
55
56
57
58
59
60
# File 'lib/more_math/numberify_string_function.rb', line 52

def convert_alphabet(alphabet)
  if alphabet.respond_to?(:to_ary)
    alphabet.to_ary
  elsif alphabet.respond_to?(:to_str)
    alphabet.to_str.split(//)
  else
    alphabet.to_a
  end
end

.numberify_string(string, alphabet = 'a'..'z') ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/more_math/numberify_string_function.rb', line 7

def numberify_string(string, alphabet = 'a'..'z')
  alphabet = NumberifyStringFunction.convert_alphabet alphabet
  s, k = string.size, alphabet.size
  result = 0
  for i in 0...s
    c = string[i, 1]
    a = (alphabet.index(c) || raise(ArgumentError, "#{c.inspect} not in alphabet")) + 1
    j = s - i - 1
    result += a * k ** j
  end
  result
end

.stringify_number(number, alphabet = 'a'..'z') ⇒ Object



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/more_math/numberify_string_function.rb', line 20

def stringify_number(number, alphabet = 'a'..'z')
  case
  when number < 0
    raise ArgumentError, "number is required to be >= 0"
  when number == 0
    return ''
  end
  alphabet = NumberifyStringFunction.convert_alphabet alphabet
  s = NumberifyStringFunction.compute_size(number, alphabet.size)
  k, m = alphabet.size, number
  result = ' ' * s
  q = m
  s.downto(1) do |i|
    r = q / k
    q = r * k < q ? r : r - 1
    result[i - 1] = alphabet[m - q * k - 1]
    m = q
  end
  result
end