Created
November 16, 2013 16:54
-
-
Save hchood/7502433 to your computer and use it in GitHub Desktop.
Ruby Fundamentals I - Challenge
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
# Ruby Fundamentals III - Challenge | |
# Write a program, given a hardcoded list of test scores, that reports the average score, the lowest score, and the highest score. | |
SCORES = [75, 100, 85, 65, 84, 87, 95] | |
def average(numbers) | |
numbers = numbers.each {|num| num.to_f} | |
sum = numbers.inject(0) {|total, num| total += num} | |
number_of_numbers = numbers.length.to_f | |
average_of_numbers = sum/number_of_numbers | |
end | |
puts "Here are the statistics:" | |
puts "Average score: #{sprintf("%.2f",average(SCORES))}" | |
puts "Lowest score: #{SCORES.min}" | |
puts "Highest score: #{SCORES.max}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice work using a method for calculating the average!
Just a quick note about the
each
method. Although you're calling theto_f
method on each number, it's not actually modifying the numbers array.to_f
will return a new object rather than modifying the number in the array but that new object isn't being stored anywhere. Instead you could write something like:Now the
floats
array contains all of the converted values and is then stored back in thenumbers
variable. Since this is a relatively common use case (converting the values in an array from one type to another) Ruby provides themap
method which will return a new array where all of the values have been converted via a code block:This is the equivalent of the above code. The
map
method is actually defined for theEnumerable
module which we'll talk about a bit later in the course: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map