-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathSumArrays.rb
37 lines (27 loc) · 976 Bytes
/
SumArrays.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
=begin
Write a method sum (sum_array in python) that takes an array of numbers and
returns the sum of the numbers. These may be integers or decimals for Ruby and
any instance of Num for Haskell. The numbers can also be negative. If the array
does not contain any numbers then you should return 0.
Examples
numbers = [1, 5.2, 4, 0, -1]
puts sum(numbers)
9.2
Assumptions
You can assume that you are only given numbers.
You cannot assume the size of the array.
You can assume that you do get an array and if the array is empty, return 0.
What We're Testing
We're testing basic loops and math operations. This is for beginners who are
just learning loops and math operations.
Disclaimer
This is for beginners so we want to test basic loops and math operations.
Advanced users may find this extremely easy and can easily write this in one line.
=end
# My Solution
def sum(numbers)
numbers != [] ? numbers.inject(:+) : 0
end
def sum(numbers)
numbers.inject(0, :+)
end