Class: BaseCustom

Inherits:
Object
  • Object
show all
Defined in:
lib/basecustom.rb,
lib/basecustom/version.rb

Constant Summary collapse

VERSION =
"1.0.2"

Instance Method Summary collapse

Constructor Details

#initialize(array_in, delim = "") ⇒ BaseCustom

Returns a new instance of BaseCustom.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/basecustom.rb', line 10

def initialize(array_in, delim = "")
  if array_in.is_a?(String)
    array_in = array_in.split(/#{delim}/)
  end
  if not array_in.is_a?(Array)
    raise "Invalid type! Please provide a String or an Array."
  end
  array_in = array_in.flatten
  if array_in.any? { |i| not i.is_a?(String) }
    raise "Invalid type! Each array element must be a String."
  end
  if !delim.is_a? String
    raise "Invalid delimiter type! Delimiter value must be a String."
  end
  if array_in.any? { |i| i.length > 1 }
   if delim.empty?
     raise "Error!  You must define a delimiter when using multiple characters for a base."
   end
  end
  @BASE_PRIMITIVES_ARRAY = array_in.uniq
  @BASE_PRIMITIVES_HASH = Hash[@BASE_PRIMITIVES_ARRAY.each_with_index.map {|x,idx| [x, idx]}]
  @delim = delim
end

Instance Method Details

#allObject



66
67
68
# File 'lib/basecustom.rb', line 66

def all
  return @BASE_PRIMITIVES_ARRAY.join(@delim)
end

#base(input_val) ⇒ Object

initialize



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/basecustom.rb', line 34

def base(input_val)
  if input_val.is_a?(String)
    if input_val.split(/#{@delim}/).any? { |i| not @BASE_PRIMITIVES_ARRAY.include?(i) }
      raise "Characters used are not in predefined base!"
    end
    i, i_out = 0, 0
    input_val.split(/#{@delim}/).reverse.each do |c|
      place = @BASE_PRIMITIVES_HASH.size ** i
      i_out += @BASE_PRIMITIVES_HASH[c] * place
      i += 1
    end
    i_out
  # end input_val.is_a?(String)
  elsif input_val.is_a?(Integer)
     return @BASE_PRIMITIVES_HASH.first[0] if input_val == 0
     number = input_val
     result = ""
     while(number != 0)
        result = @BASE_PRIMITIVES_ARRAY[number % @BASE_PRIMITIVES_ARRAY.size ].to_s + @delim + result
        number = Integer(number/@BASE_PRIMITIVES_ARRAY.size)
     end
    result
  # end input_val.is_a?(Integer)
  else
    raise "#{input_val.class} is not a supported type!"
  end
end

#lengthObject

base



62
63
64
# File 'lib/basecustom.rb', line 62

def length
  return @BASE_PRIMITIVES_ARRAY.length
end