为什么我在这里需要两个目的

时间:2015-11-03 14:37:46

标签: ruby loops

刚刚学习了一点Ruby。 这段代码工作正常但据我所知,"结束"最后是多余的。有人可以帮助我匹配我的目标吗?

def sum arr
  # YOUR CODE HERE
  total = 0
  if !arr.empty?
    arr.each do |element|
    total += element
  end
  return total
end
end

puts sum([1,2,3,4,5])

2 个答案:

答案 0 :(得分:2)

正确删除代码通常可以帮助您更轻松地发现这些问题,但我添加了注释,其中某些语句需要“结束”,以便您可以看到代码中发生的情况。

def sum arr       # A def will match up with up one 'end'
  total = 0  
  if !arr.empty?  # A if  will match up with up one 'end'
    arr.each do |element|  # A do will match up with one 'end'
      total += element
    end                    # Here's the do's end
  return total
  end               # Here's the if's end
end               # Here's the def's end

puts sum([1,2,3,4,5])

希望这有帮助!

答案 1 :(得分:1)

def sum arr
  # YOUR CODE HERE
  total = 0
  if !arr.empty?
    arr.each do |element|
      total += element
    end
    return total
  end
end

这不是多余的。在定义块时也会添加end标识符。