Created
August 18, 2014 01:09
-
-
Save akcrono/8266bf1bf60c80c17e65 to your computer and use it in GitHub Desktop.
first systems check for Launch Academy. 3 methods returning average, max, and min scores.
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 find_average scores | |
sum = 0.0 | |
scores.each do |x| | |
sum += x | |
end | |
return sum/scores.length | |
end | |
def find_max scores | |
answer = 0 | |
scores.each do |x| | |
answer = x if x > answer | |
end | |
return answer | |
end | |
def find_min scores | |
answer = scores[0] | |
scores.each do |x| | |
answer = x if x < answer | |
end | |
return answer | |
end | |
scores = [75, 100, 85, 65, 84, 87, 95] | |
puts find_average scores | |
puts find_max scores | |
puts find_min scores |
Min
Same comments as with #max
Nice job! Please put in a help request if you have any questions about any of my comments.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Max
My first suggestion for this method would be to use the local variable
max
rather thananswer
, since this method is looking for themax
:You probably don't want to initialize
max
to0
. If you were to pass in an array of values that were all less than 0, you wouldn't want to return 0 as the max. You could fix this by instead initializingmax
to be the first item in values:I know you like to optimize things and now you're thinking "oh no! I don't want to iterate over the same value that it's already set to and compare it with itself! What can I do!?":
You can
#pop
the first value which will remove it from the array and it won't be iterated over later in the#each
block:An alternative solution could be written, again using
#inject
: