You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.28 11:07:32