Last active
January 2, 2016 09:59
-
-
Save carolineartz/8286285 to your computer and use it in GitHub Desktop.
.each vs. .length.times and TypeError
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
#total sum of array .each vs. .length.times | |
#using .length.times | |
def total(array) | |
sum = 0 | |
#The length method returns the size of the array. | |
#Here, adding .times iterates the following block length times... | |
array.length.times do |x| | |
#...since the use of .times passes the parameter, x, 0 through (length -1), | |
#the block needs to get the value the array elements via index. | |
#your code reflects this | |
#so this is why it works here | |
sum += array[x] #works: add value at array index 0 through length-1 (i.e., all of them) to sum | |
end | |
sum | |
end | |
#using .each | |
def total(array) | |
sum = 0 | |
#.each evaluates the block once for each element of the array | |
array.each do | x | # here, the parameter, x, references the actual value of the array elements | |
#so summing the total calls for simply adding x, and not the array value AT INDEX x | |
sum += x | |
end | |
sum | |
end | |
Another good exercise would be to follow through with ruby-docs to make sense of what's going on.
In your code, by introducing the right block onto the .times
method, you were able to sum the elements with their indices in exactly the amount of times required. It's a pretty interesting chain method.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Caroline.
Thanks for taking the time to put this together. After reading through your notes it makes sense.