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 hidden or 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
eachmethod. Although you're calling theto_fmethod on each number, it's not actually modifying the numbers array.to_fwill 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
floatsarray contains all of the converted values and is then stored back in thenumbersvariable. Since this is a relatively common use case (converting the values in an array from one type to another) Ruby provides themapmethod 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
mapmethod is actually defined for theEnumerablemodule which we'll talk about a bit later in the course: http://ruby-doc.org/core-1.9.3/Enumerable.html#method-i-map