Class: StringNumber
- Inherits:
-
Object
- Object
- StringNumber
- Defined in:
- lib/string_number.rb
Constant Summary collapse
- SYMBOLS =
Hash[('A'..'Z').each_with_index.map{|s,i| [s,i+1]
Class Method Summary collapse
Instance Method Summary collapse
- #+(value) ⇒ Object
- #-(value) ⇒ Object
- #==(other) ⇒ Object
- #eql?(other) ⇒ Boolean
-
#initialize(value) ⇒ StringNumber
constructor
A new instance of StringNumber.
- #to_i ⇒ Object
- #to_s ⇒ Object
Constructor Details
#initialize(value) ⇒ StringNumber
Returns a new instance of StringNumber.
4 5 6 7 |
# File 'lib/string_number.rb', line 4 def initialize(value) raise ArgumentError, "Invalid value for #{self.class.name} (#{value})" unless self.class.valid(value) @value = value.upcase end |
Class Method Details
.[](number) ⇒ Object
40 41 42 43 44 45 46 47 48 |
# File 'lib/string_number.rb', line 40 def self.[](number) return self.new(SYMBOLS.keys[number-1]) if number <= SYMBOLS.count quotient = number / base reminder = number % base quotient -= 1 if reminder == 0 recursive = self[quotient].to_s if quotient > 0 self.new((recursive || '') + SYMBOLS.keys[reminder-1]) end |
.base ⇒ Object
50 51 52 |
# File 'lib/string_number.rb', line 50 def self.base SYMBOLS.count end |
.valid(string) ⇒ Object
54 55 56 57 |
# File 'lib/string_number.rb', line 54 def self.valid(string) return false unless string.is_a? String string.match(/[A-Z]*/i).to_s == string end |
Instance Method Details
#+(value) ⇒ Object
9 10 11 |
# File 'lib/string_number.rb', line 9 def +(value) self.class[to_i + number_of(value)] end |
#-(value) ⇒ Object
13 14 15 16 17 18 |
# File 'lib/string_number.rb', line 13 def -(value) number = number_of(value) result = to_i - number raise StandardError, "Cant substract from #{number} to #{to_s}" if result < 1 self.class[result] end |
#==(other) ⇒ Object
25 26 27 28 |
# File 'lib/string_number.rb', line 25 def ==(other) return false unless other.is_a? self.class to_s == other.to_s end |
#eql?(other) ⇒ Boolean
20 21 22 23 |
# File 'lib/string_number.rb', line 20 def eql?(other) return false unless other.is_a? self.class to_s.eql?(other.to_s) end |
#to_i ⇒ Object
34 35 36 37 38 |
# File 'lib/string_number.rb', line 34 def to_i segments = @value.reverse.split('') units = segments.each_with_index.map{ |s,i| SYMBOLS[s] * self.class.base**i } units.inject(:+) end |
#to_s ⇒ Object
30 31 32 |
# File 'lib/string_number.rb', line 30 def to_s @value end |