Skip to content

Instantly share code, notes, and snippets.

@eveadele
Created February 23, 2014 17:38
Show Gist options
  • Save eveadele/9174548 to your computer and use it in GitHub Desktop.
Save eveadele/9174548 to your computer and use it in GitHub Desktop.
list = [75, 100, 85, 65, 84, 87, 95]
def highest(list_given)
maximum = 0
list_given.each do |item|
if item > maximum
maximum = item
end
end
return maximum
end
def lowest(list_given)
minimum = list_given[0]
list_given.each do |item|
if item < minimum
minimum = item
end
end
return minimum
end
def add_up_list(list_given)
total = 0
list_given.each do |item|
total += item
end
total
end
def list_size(list_given)
size = 0
list_given.each do |item|
size += 1
end
size
end
def average(sum, list_given_size)
sum / list_given_size
end
puts "Highest: #{highest(list)}"
puts "Lowest: #{lowest(list)}"
puts "Average: #{average(add_up_list(list), list_size(list))}"
@HeroicEric
Copy link

Be careful about leaving trailing whitespace in your files. You've got a blank space on the lines that are separating your methods:

Trailing Whitespace

Make sure you've got all of the Sublime Text settings provided in the install guide. Here they are again https://gist.github.com/HeroicEric/77c860d2fe8d7ae0a98f

@HeroicEric
Copy link

The explicit returns at the end of #highest and #lowest aren't necessary. http://stackoverflow.com/questions/1023146/is-it-good-style-to-explicitly-return-in-ruby

@HeroicEric
Copy link

I'm not sure if your #list_size method is necessary. Since your list is already an Array, you can just use Array#length.

list.length

@HeroicEric
Copy link

I would probably refactor your #add_up_list method to be more generic/reusable:

def sum(values)
  sum = 0

  values.each do |value|
    sum += value
  end

  sum
end

Another option here could be to use the Enumerable#inject.

# This will initialize `sum` as 0 and add the `value` to the `sum` with each iteration.
# The value of `sum` is what will be eventually returned.
def sum(values)
  values.inject(0) do |sum, value|
    sum += value
  end
end

You could also take it a step further and use a shorthand version of inject like this:

def sum(values)
  values.inject(:+)
end

More info about the crazy shorthand at http://www.potstuck.com/2011/08/06/ruby-symbols-instead-of-blocks/

Also, it's totally cool to write it out the way you did.#inject can be tricky to get the hang of. I just wanted to point out that it exists.

@HeroicEric
Copy link

Nice job!

@eveadele
Copy link
Author

I think gists add whitespace? I have all the Sublime Text settings, and when I open up the file in Sublime there's no whitespace. But thanks for all the feedback!

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