Ruby语法错误求助:unexpected `end', expecting end-of-input报错排查
解决Ruby中
syntax error, unexpected end, expecting end-of-input的问题 Hey there! Let's dig into your code and fix that frustrating syntax error. The root cause is a small but critical mistake in how you set up the iterator block, which throws off Ruby's parsing of your end statements.
问题定位
Your line from.upto(to) |num| is missing the do keyword that Ruby expects to start a block paired with end. Without it, Ruby can't properly recognize where the iteration block begins, leading to the mismatched end error you're seeing.
修正后的完整代码
def total2(from, to, &block) result = 0 from.upto(to) do |num| # 添加do关键字,修正块的起始语法 if block result += block.call(num) else result += num end end return result end p total2(1, 10) # 输出 55 p total2(1, 10){|num| num ** 2} # 输出 385
关键修正点
- 迭代块语法修复: 把
from.upto(to) |num|改为from.upto(to) do |num|,这是Ruby定义多行块的标准写法(你也可以用from.upto(to) { |num| ... },但多行块用do...end更易读)。 end语句匹配: 现在每个do都有对应的end,函数的end也能正确匹配函数定义的起始,Ruby可以顺利解析整个代码结构了。
运行修正后的代码,你就能得到预期的累加结果啦!
内容的提问来源于stack exchange,提问作者TPR
相关产品推荐
相关产品推荐

