Created
February 23, 2014 01:20
-
-
Save adeng21/9165230 to your computer and use it in GitHub Desktop.
Week 1 Checkpoint
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
scores = [75, 100, 85, 65, 84, 87, 95] | |
def average(array) | |
total = 0 | |
array.each {|i| total += i} | |
total/array.length | |
end | |
def highest(array) | |
first = array[0] | |
array.each do |i| | |
if i > first | |
first = i | |
end | |
end | |
return first | |
end | |
def lowest(array) | |
first = array[0] | |
array.each do |i| | |
if i < first | |
first = i | |
end | |
end | |
return first | |
end | |
puts "Average Score: #{average(scores)}" | |
puts "Highest Score: #{highest(scores)}" | |
puts "Lowest Score: #{lowest(scores)}" |
inside your def average
method, you could extract the sum of an array into its own method:
def average(array)
sum(array) / array.length
end
def sum(array)
array.inject { |sum, x| sum + x }
end
in your highest and lowest methods, replace i and first with more expressive variable names. first is misleading because it doesn't return the first element, it returns the min or max.
otherwise, great job!
The only thing I'd add is to convert to floats instead of integers so that you get more precise results
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
instead of using
array.each
you could use.inject
. Then you wouldn't have to initialize total = 0