Module: MoreMath::NumberifyStringFunction
- Included in:
- StringNumeral
- Defined in:
- lib/more_math/numberify_string_function.rb
Constant Summary collapse
Class Method Summary collapse
- .compute_size(n, b) ⇒ Object
- .convert_alphabet(alphabet) ⇒ Object
- .numberify_string(string, alphabet = 'a'..'z') ⇒ Object
- .stringify_number(number, alphabet = 'a'..'z') ⇒ Object
Class Method Details
.compute_size(n, b) ⇒ Object
45 46 47 48 49 50 51 52 |
# File 'lib/more_math/numberify_string_function.rb', line 45 def compute_size(n, b) i = 0 while n > 0 i += 1 n -= b ** i end i end |
.convert_alphabet(alphabet) ⇒ Object
55 56 57 58 59 60 61 62 63 |
# File 'lib/more_math/numberify_string_function.rb', line 55 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
10 11 12 13 14 15 16 17 18 19 20 21 |
# File 'lib/more_math/numberify_string_function.rb', line 10 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
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/more_math/numberify_string_function.rb', line 23 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 |