Created
May 22, 2014 06:21
-
-
Save yoshprogrammer/a4f278c63589ce73334a to your computer and use it in GitHub Desktop.
Exercise Four
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
# Things we'll need: | |
# 1. Something to keep track of the running total | |
# 2. Something that goes through the list one number at a time | |
# 3. Something that adds the current number to the running total | |
# | |
# For (3), consider these bits of Ruby: | |
# total = 10 # assign the value 10 to the variable "total" | |
# total = total + 5 # the value of "total" is now 15 | |
# total = total + 20 # the value of "total" is now 35 | |
# total = total + 7 # the value of "total" is now 42 | |
# total = total - 10 # the value of "total" is now 32 (notice the minus) | |
# total = total + 70 # the value of "total" is now 102 | |
def sum(list) | |
list.inject(0) do |total, num| #From my understanding from various resources, this basically says start at 0 and | |
total += num # add the first item in the list which becomes total, and then the next item is added | |
end # as num to total. Once completed, from my understanding, .inject has logic that | |
# tells it to return the value | |
end | |
p sum([1]) | |
p sum([0]) | |
p sum([-1]) | |
p sum([1, -1]) | |
p sum([0, 10, 0, 20]) | |
p sum([-111, -111, -111]) | |
p sum([11,22,33]) | |
# Questions: | |
# 1.) How do I get it to return per line, isn't that the point of this exercise? For instance, how would I get it to return | |
# each value, such as line 35's list "total = 0" on one line, next "total = 0 + 11", next line "total = 11+22". | |
# I could not find a way to do it like, 'running_total = return item[0], return item[0] + item[1]...item[i]'. | |
# 2.) Where do you guys go to start when trying to find a method? Is there a method I should be following when I do not | |
# know where to start? I checked the technical documentation but didn't find it there. I will admit I am not comfortable | |
# just yet with reading/comprehending all of it. I then googled 'each loop running total ruby' and looked around stack | |
# overflow which had a link to enumerables technical docs which then lead to some experimenting and possible success. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment