.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