Class: Tuwaga
- Inherits:
-
Object
- Object
- Tuwaga
- Defined in:
- lib/tuwaga.rb
Instance Attribute Summary collapse
-
#base ⇒ Object
readonly
Returns the value of attribute base.
-
#symbol_value_map ⇒ Object
readonly
Returns the value of attribute symbol_value_map.
-
#symbols ⇒ Object
readonly
Returns the value of attribute symbols.
Instance Method Summary collapse
- #convert_from(value, number_base) ⇒ Object
- #convert_to(value, number_base) ⇒ Object
- #from_decimal(input) ⇒ Object
-
#initialize(base = 10, symbols = nil) ⇒ Tuwaga
constructor
A new instance of Tuwaga.
- #to_decimal(input) ⇒ Object
Constructor Details
#initialize(base = 10, symbols = nil) ⇒ Tuwaga
Returns a new instance of Tuwaga.
4 5 6 7 8 9 10 11 12 13 |
# File 'lib/tuwaga.rb', line 4 def initialize base = 10, symbols = nil @base = base validate_base @symbols = blank?(symbols) ? guess_symbols : symbols.split('') validate_symbols @symbol_value_map = {} @symbols.each_with_index { |item, index| @symbol_value_map[item] = index } end |
Instance Attribute Details
#base ⇒ Object (readonly)
Returns the value of attribute base.
2 3 4 |
# File 'lib/tuwaga.rb', line 2 def base @base end |
#symbol_value_map ⇒ Object (readonly)
Returns the value of attribute symbol_value_map.
2 3 4 |
# File 'lib/tuwaga.rb', line 2 def symbol_value_map @symbol_value_map end |
#symbols ⇒ Object (readonly)
Returns the value of attribute symbols.
2 3 4 |
# File 'lib/tuwaga.rb', line 2 def symbols @symbols end |
Instance Method Details
#convert_from(value, number_base) ⇒ Object
50 51 52 53 54 55 |
# File 'lib/tuwaga.rb', line 50 def convert_from value, number_base raise 'Value must be a String' if (!value.is_a?(String)) raise 'Number_base must be an instance of Tuwaga' if (!number_base.is_a?(Tuwaga)) from_decimal(number_base.to_decimal(value)) end |
#convert_to(value, number_base) ⇒ Object
43 44 45 46 47 48 |
# File 'lib/tuwaga.rb', line 43 def convert_to value, number_base raise 'Value must be a String' if (!value.is_a?(String)) raise 'Number_base must be an instance of Tuwaga' if (!number_base.is_a?(Tuwaga)) number_base.from_decimal(to_decimal(value)) end |
#from_decimal(input) ⇒ Object
28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/tuwaga.rb', line 28 def from_decimal input raise 'Input must be an integer' if (!input.is_a?(Integer)) return @symbols[0] if input == 0 result = '' in_decimal = input while (in_decimal > 0) do result = @symbols[in_decimal % @base] + result in_decimal = in_decimal / @base end result end |
#to_decimal(input) ⇒ Object
15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/tuwaga.rb', line 15 def to_decimal input raise 'Input must be a string' if (!input.is_a?(String)) result = 0 power = 0 input.split('').reverse.each do |char| result += @symbol_value_map[char] * (@base ** power) power += 1 end result end |