Class: BaseAnything::NumberSystem
- Inherits:
-
Object
- Object
- BaseAnything::NumberSystem
show all
- Defined in:
- lib/baseanything.rb
Instance Method Summary
collapse
Constructor Details
Returns a new instance of NumberSystem.
4
5
6
7
|
# File 'lib/baseanything.rb', line 4
def initialize(arr)
@correspondences = make_correspondance_hash(arr)
@base = arr.length
end
|
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(name, num) ⇒ Object
52
53
54
55
56
57
58
59
60
61
|
# File 'lib/baseanything.rb', line 52
def method_missing(name, num)
name = name.to_s
if name[0..2] == "to_"
base = FIND_BASE["#{name[3..-1]}"]
to_base(num, base)
elsif name[0..4] == "from_"
base = FIND_BASE["#{name[5..-1]}"]
from_base(num, base)
end
end
|
Instance Method Details
#from_base(num, base) ⇒ Object
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
|
# File 'lib/baseanything.rb', line 29
def from_base(num, base)
num = other_to_dec(num, base)
output = ""
highest_quot = 0
while (@base ** (highest_quot+1) <= num)
highest_quot += 1
end
while highest_quot >= 0
next_digit = num / (@base ** highest_quot)
digit_value = @correspondences.select{|k,v| @correspondences[k.to_s] == next_digit}
output << digit_value.keys[0]
to_remove = next_digit * (@base ** highest_quot)
num -= to_remove
highest_quot -= 1
end
output
end
|
#to_base(num, base) ⇒ Object
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
# File 'lib/baseanything.rb', line 9
def to_base(num, base)
num = own_to_dec(num)
output = ""
highest_quot = 0
while (base ** (highest_quot+1)) <= num
highest_quot += 1
end
while highest_quot >= 0
next_digit = num / (base ** highest_quot)
output << ANY_BASE[next_digit.to_s]
to_remove = next_digit * (base ** highest_quot)
num -= to_remove
highest_quot -= 1
end
output
end
|