Class: BaseN::Encoder
- Inherits:
-
Object
- Object
- BaseN::Encoder
- Defined in:
- lib/base_n.rb
Constant Summary collapse
- PRIMITIVES =
((0..9).collect { |i| i.to_s } + ('A'..'Z').to_a + ('a'..'z').to_a + %w(! " # $ % & ' ( ) * + , - . / : ; < = > ? @ [ \\ ] ^ _ ` { | } ~)).map(&:freeze).freeze
Instance Attribute Summary collapse
-
#base ⇒ Object
Returns the value of attribute base.
Class Method Summary collapse
Instance Method Summary collapse
- #case_sensitive? ⇒ Boolean
- #decode(subject) ⇒ Object
- #encode(subject) ⇒ Object
-
#initialize(base) ⇒ Encoder
constructor
A new instance of Encoder.
- #primitives ⇒ Object
Constructor Details
#initialize(base) ⇒ Encoder
Returns a new instance of Encoder.
23 24 25 26 27 |
# File 'lib/base_n.rb', line 23 def initialize base self.base = base raise "I only support bases 2 and above" if base < 2 raise "I only support up to base #{primitives.size}" if base > primitives.size end |
Instance Attribute Details
#base ⇒ Object
Returns the value of attribute base.
21 22 23 |
# File 'lib/base_n.rb', line 21 def base @base end |
Class Method Details
.highest_supported ⇒ Object
29 30 31 |
# File 'lib/base_n.rb', line 29 def self.highest_supported new PRIMITIVES.size end |
Instance Method Details
#case_sensitive? ⇒ Boolean
33 34 35 |
# File 'lib/base_n.rb', line 33 def case_sensitive? base > 36 end |
#decode(subject) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/base_n.rb', line 41 def decode subject r = subject.representation r.upcase! unless Encoder.new(subject.base).case_sensitive? s = r.reverse.split('') total = 0 s.each_with_index do |char, index| if ord = primitives.index(char) total += ord * (base ** index) else raise ArgumentError, "#{subject} has #{char} which is not valid" end end total end |
#encode(subject) ⇒ Object
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/base_n.rb', line 57 def encode subject subject = Number.new subject.to_s, 10 unless subject.kind_of? BaseN::Number return subject if subject.base == base i = Encoder.new(subject.base).decode(subject) s = '' while i > 0 s << primitives[i.modulo(base)] i /= base end s = '0' if s == '' Number.new s.reverse, base end |
#primitives ⇒ Object
37 38 39 |
# File 'lib/base_n.rb', line 37 def primitives PRIMITIVES[0, base] end |