Class: Integer

Inherits:
Object
  • Object
show all
Defined in:
lib/to_insane.rb

Instance Method Summary collapse

Instance Method Details

#to_insane(base_val = nil, alpha = nil) ⇒ Object

Converts a base10 integer to a base x string.

Raises:

  • (ArgumentError)


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/to_insane.rb', line 33

def to_insane(base_val = nil, alpha = nil)
  alpha ||= INSANECHARACTERS
  base_val ||= 58
  base_val = alpha.size if base_val == :max
  if base_val == :url_safe
    base_val = 63
    alpha = INSANECHARACTERS
  end
  raise ArgumentError, "Base Value is not valid. Integer, :max, :url_safe" unless base_val.kind_of? Integer
  raise ArgumentError, "Base size is too large for given character set. Please use a Base value larger than 1 and less than #{alpha.length}" if base_val > alpha.length or base_val <= 2
  raise ArgumentError, "Character set needs to be larger than 0" if alpha.size <= 0
  raise ArgumentError, "Character set has duplicate characters" if alpha.size != alpha.split(//).uniq.size
  char_ref = alpha[0..base_val]
  insane_val = ''
  int_val = self 
  while(int_val >= base_val)
    mod = int_val % base_val
    insane_val = char_ref[mod,1] + insane_val
    int_val = (int_val - mod)/base_val
  end
  char_ref[int_val,1] + insane_val
end