Skip to content

Instantly share code, notes, and snippets.

@hchood
Created November 16, 2013 16:54
Show Gist options
  • Save hchood/7502433 to your computer and use it in GitHub Desktop.
Save hchood/7502433 to your computer and use it in GitHub Desktop.
Ruby Fundamentals I - Challenge
# 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}"
@atsheehan
Copy link

Nice work using a method for calculating the average!

Just a quick note about the each method. Although you're calling the to_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:

numbers = [75, 100, 85, 65]

floats = []
numbers.each do |num| 
  floats << num.to_f
end

numbers = floats

Now the floats array contains all of the converted values and is then stored back in the numbers variable. Since this is a relatively common use case (converting the values in an array from one type to another) Ruby provides the map method which will return a new array where all of the values have been converted via a code block:

numbers = numbers.map { |num| num.to_f }

This is the equivalent of the above code. The map method is actually defined for the Enumerable 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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment