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.
5
6
7
8
|
# File 'lib/baseanything.rb', line 5
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
51
52
53
54
55
56
57
58
59
60
|
# File 'lib/baseanything.rb', line 51
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
#add(num1, num2) ⇒ Object
62
63
64
65
|
# File 'lib/baseanything.rb', line 62
def add(num1, num2)
decimal = own_to_dec(num1) + own_to_dec(num2)
from_base(decimal.to_s, 10)
end
|
#divide(num1, num2) ⇒ Object
77
78
79
80
|
# File 'lib/baseanything.rb', line 77
def divide(num1, num2)
decimal = own_to_dec(num1) / own_to_dec(num2)
from_base(decimal.to_s, 10)
end
|
#exponent(num1, num2) ⇒ Object
87
88
89
90
|
# File 'lib/baseanything.rb', line 87
def exponent(num1, num2)
decimal = own_to_dec(num1) ** own_to_dec(num2)
from_base(decimal.to_s, 10)
end
|
#from_base(num, base) ⇒ Object
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
# File 'lib/baseanything.rb', line 30
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
|
#modulo(num1, num2) ⇒ Object
82
83
84
85
|
# File 'lib/baseanything.rb', line 82
def modulo(num1, num2)
decimal = own_to_dec(num1) % own_to_dec(num2)
from_base(decimal.to_s, 10)
end
|
#multiply(num1, num2) ⇒ Object
72
73
74
75
|
# File 'lib/baseanything.rb', line 72
def multiply(num1, num2)
decimal = own_to_dec(num1) * own_to_dec(num2)
from_base(decimal.to_s, 10)
end
|
#subtract(num1, num2) ⇒ Object
67
68
69
70
|
# File 'lib/baseanything.rb', line 67
def subtract(num1, num2)
decimal = own_to_dec(num1) - own_to_dec(num2)
from_base(decimal.to_s, 10)
end
|
#to_base(num, base) ⇒ Object
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
# File 'lib/baseanything.rb', line 10
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
|