Skip to content

Instantly share code, notes, and snippets.

@carolineartz
Last active January 2, 2016 09:59
Show Gist options
  • Save carolineartz/8286285 to your computer and use it in GitHub Desktop.
Save carolineartz/8286285 to your computer and use it in GitHub Desktop.
.each vs. .length.times and TypeError
#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
@carolineartz
Copy link
Author

for readability, it might help to copy/paste the gist into Sublime to make the comments vs. code clearer.... :)

@micodel
Copy link

micodel commented Jan 6, 2014

Hi Caroline.

Thanks for taking the time to put this together. After reading through your notes it makes sense.

  • Michael

@kanhirun
Copy link

kanhirun commented Jan 6, 2014

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