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

在线Ruby编辑器报undefined method `chomp'错误,如何修复?

问题原因与修复方案

undefined method 'chomp' for nil:NilClass错误原因

这不是编辑器的问题,而是在线运行环境的输入机制导致的:

  • 本地Ruby环境是交互式的,运行时会等待用户输入,gets能正常捕获内容。但你使用的在线编辑器需要提前预设所有交互输入内容,如果没预设,gets会返回nil,调用chomp自然触发该错误。
  • 你的代码本身还有语法、逻辑错误,也会导致运行异常。

代码中的其他问题

  • 字符串插值语法错误:Ruby中字符串插值必须放在双引号内,比如puts #{first_name.reverse}要改成puts "#{first_name.reverse}";后面的#{first_name!}是错误写法,感叹号多余,应为#{first_name}。
  • 逻辑错误:你直接把yes = true,没有获取用户是否反转名字的输入,导致if yes分支永远执行,else分支完全失效。
  • 拼写错误:多处you're误用,比如"What's you're name?"应该是"What's your name?"(your是物主代词,you're是you are的缩写,此处不符合语境)。

修复后的代码

print "What's your first name? "
first_name = gets&.chomp || ""
print "What's your last name? "
last_name = gets&.chomp || ""
print "What city are you from? "
city = gets&.chomp || ""
print "Want to see your name backwards? (yes/no) "
response = gets&.chomp&.downcase

if response == "yes"
  puts "Your reversed full name: #{(first_name + " " + last_name).reverse}"
else
  puts "Ok!"
  puts "Your first name is: #{first_name}"
  puts "Your last name is: #{last_name}"
  puts "Your city is: #{city}"
end

在线编辑器使用注意事项

在该在线编辑器运行代码时,需要:

  1. 找到页面上的**"Stdin Input"**区域(通常在代码框下方)。
  2. 提前输入所有交互内容,每行对应一个gets的输入,示例输入:
    Alice
    Smith
    New York
    yes
    
  3. 点击运行按钮,gets就能正确捕获输入内容,不会返回nil。

内容的提问来源于stack exchange,提问作者need help

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 20:35:28