Created
September 4, 2014 18:49
-
-
Save noqcks/b946349d92b1e542a14a to your computer and use it in GitHub Desktop.
w1d3
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def average(numbers) | |
sum = 0 | |
numbers.each do |num| | |
sum += num | |
end | |
if numbers.empty? || numbers.nil? | |
0 | |
else | |
sum / numbers.size | |
end | |
end | |
## TEST HELPER METHOD | |
def test_average(array=nil) | |
if array != nil | |
array = array.compact | |
print "avg of #{array.inspect}:" | |
result = average(array) | |
puts result | |
else | |
puts "There is no array here: 0" | |
end | |
end | |
## TEST CODE | |
test_average([4,5,6]) # => 5 | |
test_average([15,5,10]) # => 10 | |
# Should treat string like number | |
test_average([15,5,10]) # => 5 | |
# Should show decimal value | |
test_average([10.0,5]) # => 7.5 instead of just 7 | |
########## Empty set should return 0 as average, not throw an error | |
test_average([]) # => 0 | |
########## Non-existent set should return 0 | |
test_average() # => 0 | |
########### BONUS: Should ignore nils in the set | |
test_average([9,6,nil,3]) # => 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment