-
Notifications
You must be signed in to change notification settings - Fork 68
Expand file tree
/
Copy pathSimpleMaths.rb
More file actions
42 lines (35 loc) · 793 Bytes
/
SimpleMaths.rb
File metadata and controls
42 lines (35 loc) · 793 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
=begin
Description:
In this kata, you will do addition and subtraction on a given string.
The return value must be a 'string'.
Example: calculate('1plus2plus3minus4') should return '2'.
=end
# My Solution
def calculate(str)
num1 = "" ; result = []
str.gsub!("plus","+")
str.gsub!("minus","-")
str.split("").each_with_index do |x,i|
if x =~ /\d/
num1 += x
else
result << num1.to_i
result << x
num1 = ""
end
end
result << num1
return_value = result[0].to_i
1.upto(result.length-1) do |x|
if x.odd?
result[x] == "+" ? return_value += result[x+1].to_i : return_value -= result[x+1].to_i
end
end
return_value.to_s
end
# Better Soltuion
def calculate(s)
s = s.gsub('plus', '+')
s = s.gsub('minus','-')
eval(s).to_s
end