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的主要内容,如果未能解决你的问题,请参考以下文章

Ruby:在 each、map、inject、each_with_index 和 each_with_object 之间进行选择

在 Ruby 中,#each_pair 在遍历哈希时比 #each 有啥优势?

Ruby 中的“temps.each(&:valid?)”是啥意思? [复制]

ruby 2.0,为啥#each_line 变异文件对象

Swift 相当于 Ruby 的 "each_cons"

Ruby if else 在 array.each