Module: SleepingKingStudios::Tools::IntegerTools
- Extended by:
- IntegerTools
- Included in:
- IntegerTools
- Defined in:
- lib/sleeping_king_studios/tools/integer_tools.rb
Overview
Tools for working with integers and fixnums.
Constant Summary collapse
- ROMANIZE_MIN =
Minimum integer value that can be converted to a roman numeral.
1- ROMANIZE_MAX =
Maximum integer value that can be converted to a roman numeral.
4999
Instance Method Summary collapse
-
#count_digits(integer, base: 10) ⇒ Integer
Returns the number of digits in the given integer when represented in the specified base.
-
#digits(integer, base: 10) ⇒ Array<String>
Decomposes the given integer into its digits when represented in the given base.
-
#romanize(integer, additive: false) ⇒ String
Represents an integer between 1 and 4999 (inclusive) as a Roman numeral.
Instance Method Details
#count_digits(integer, base: 10) ⇒ Integer
Returns the number of digits in the given integer when represented in the specified base. Ignores minus sign for negative numbers.
40 41 42 |
# File 'lib/sleeping_king_studios/tools/integer_tools.rb', line 40 def count_digits integer, base: 10 digits(integer.abs, :base => base).count end |
#digits(integer, base: 10) ⇒ Array<String>
Decomposes the given integer into its digits when represented in the given base.
65 66 67 |
# File 'lib/sleeping_king_studios/tools/integer_tools.rb', line 65 def digits integer, base: 10 integer.to_s(base).split('') end |
#romanize(integer, additive: false) ⇒ String
Represents an integer between 1 and 4999 (inclusive) as a Roman numeral.
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 |
# File 'lib/sleeping_king_studios/tools/integer_tools.rb', line 88 def romanize integer, additive: false # Validate input value. unless (ROMANIZE_MIN..ROMANIZE_MAX).include? integer raise RangeError.new "integer to romanize must be within range #{ROMANIZE_MIN} to #{ROMANIZE_MAX}" end # unless # Define conversion rules. rules = [ '', '%one', '%one%one', '%one%one%one', additive ? '%one%one%one%one' : '%one%five', '%five', '%five%one', '%five%one%one', '%five%one%one%one', additive ? '%five%one%one%one%one' : '%one%ten', '%ten' ] # end array # Define numeral values. numerals = [ %w(I V X), %w(X L C), %w(C D M), ['M', 'MMM', ''] ] # end array numerals # Generate string representation. digits(integer).reverse.map.with_index do |digit, index| rules[digit.to_i] .gsub('%one', numerals[index][0]) .gsub('%five', numerals[index][1]) .gsub('%ten', numerals[index][2]) end.reverse.join '' end |