Skip to content

Instantly share code, notes, and snippets.

@allcentury
Created February 22, 2014 15:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save allcentury/9156808 to your computer and use it in GitHub Desktop.
Save allcentury/9156808 to your computer and use it in GitHub Desktop.
test_scores = [75, 100, 85, 65, 84, 87, 95]
def avg(array)
sum = 0.0
array.each do |x|
sum += x
end
(sum / array.length).round(2)
end
def lowest(array)
lowest = array[0]
array.each do |x|
if x < lowest
lowest = x
end
end
lowest
end
def highest(array)
max = array[0]
array.each do |x|
if x > max
max = x
end
end
max
end
puts "Average score: #{avg(test_scores)}"
puts "Lowest score: #{lowest(test_scores)}"
puts "Highest score: #{highest(test_scores)}"
@hchood
Copy link

hchood commented Feb 24, 2014

Great work! This looks awesome.

If you wanted to shorten things up a tiny bit, you can use one-line syntax for do...end and if blocks:

def avg(array)
  sum = 0.0
  array.each { |x| sum += x }
  (sum / array.length).round(2)
end
def lowest(array)
  lowest = array[0]
  array.each { |x| lowest = x if x < lowest }
  lowest
end

I'd only use that syntax if you have just one line of code to run inside your block, although I think Sandi Metz uses curly braces for larger blocks.

Also, you can use inject to calculate the sum of an array of numbers.

Great job!

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