class Rebase

Constants

B36
B62

Attributes

alphabet[R]
base[R]

Public Class Methods

new(alphabet) click to toggle source
# File lib/rebase.rb, line 4
def initialize(alphabet)
  @alphabet =
    case alphabet
    when :binary then get_base(2)
    when :hex    then get_base(16)
    when Fixnum  then get_base(alphabet)
    when Array   then build_alphabet(alphabet)
    else         raise ArgumentError, 'Invalid input'
    end
  @base = @alphabet.size
end

Public Instance Methods

decode(str) click to toggle source
# File lib/rebase.rb, line 22
def decode(str)
  raise ArgumentError, 'String cant be empty' if str.empty?
  decode_rec(0, 0, str)
end
encode(int) click to toggle source
# File lib/rebase.rb, line 16
def encode(int)
  raise ArgumentError, 'Integer cant be negative' if int < 0
  return alphabet[int] if int.zero?
  encode_rec('', int)
end

Private Instance Methods

alphabet_index() click to toggle source
# File lib/rebase.rb, line 42
def alphabet_index
  @alphabet_index ||= begin
    Hash[alphabet.each_with_index.to_a].tap do |h|
      h.default_proc = proc do |_,k|
        raise ArgumentError, "Invalid character in input: #{k}"
      end
    end
  end
end
build_alphabet(array) click to toggle source
# File lib/rebase.rb, line 52
def build_alphabet(array)
  raise ArgumentError, "Alphabet to short" if array.size < 2
  array.map(&:to_s)
end
decode_rec(acc, pow, str) click to toggle source
# File lib/rebase.rb, line 35
def decode_rec(acc, pow, str)
  return acc if str.empty?
  decode_rec(base ** pow * alphabet_index[str[-1]] + acc,
             pow.next,
             str[0...-1])
end
encode_rec(acc, int) click to toggle source
# File lib/rebase.rb, line 29
def encode_rec(acc, int)
  return acc if int.zero?
  encode_rec(alphabet[int % base] + acc,
             int / base)
end
get_base(int) click to toggle source
# File lib/rebase.rb, line 57
def get_base(int)
  raise ArgumentError, "Invalid base: #{int}" if int < 2 || int > 62
  (int > 36 ? B62 : B36)[0...int]
end