ruby .each vs. .length.times和TypeError

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ruby .each vs. .length.times和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

以上是关于ruby .each vs. .length.times和TypeError的主要内容,如果未能解决你的问题,请参考以下文章