-
Notifications
You must be signed in to change notification settings - Fork 0
/
sum.rb
57 lines (46 loc) · 904 Bytes
/
sum.rb
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
def sum(array)
total = 0
i = 0
while i < array.length
total = total + array[i]
i = i + 1
end
total
end
# turn local variables into default arguments (chop off head)
def sum(array, total = 0, i = 0)
while i < array.length
total = total + array[i]
i = i + 1
end
total
end
# turn loop condition into a conditional return (chop off tail)
def sum(array, total = 0, i = 0)
loop do
if i < array.length
total = total + array[i]
i = i + 1
else
return total
end
end
end
# replace next loop iteration with recursive call
def sum(array, total = 0, i = 0)
if i < array.length
total = total + array[i]
i = i + 1
return sum(array, total, i)
else
return total
end
end
# *general refactoring noises*
def sum(array, total = 0, i = 0)
if i < array.length
sum(array, total + array[i], i + 1)
else
total
end
end