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 | |
for readability, it might help to copy/paste the gist into Sublime to make the comments vs. code clearer.... :)
Hi Caroline.
Thanks for taking the time to put this together. After reading through your notes it makes sense.
- Michael
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
So, to address the error you get when you use .each and parameter x , I believe getting a
nil can't be coerced into Fixnum (TypeError)
would result from attempting to add to the array the value at an index that is outside the array bounds (e.g., a 3-element array with one value of 6 would look to append the sum with the value of the array at index 6). When that happens, it tries to addnil
to the Fixnum and gives you an error.Anyone else have thoughts on this or know if this is on the right track for interpreting the error?