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

Ruby中无法对用户输入的年龄字符串执行除法运算求助

Fixing Your Age Calculation Ruby Code

Hey there, let's get your Ruby script working properly! I’ve spotted two key issues that are stopping it from running as expected:

1. Type Mismatch When Doing Division

The gets.chomp method returns a string even if the user enters a number. So when you try to run age/2, you’re asking Ruby to divide a string by an integer—this will throw a TypeError because those types don’t play nice together.

Fix this by converting the input to an integer right away:

age = gets.chomp.to_i

2. Invalid String Concatenation

When you use + to combine strings with non-string values (like the result of age/2, which is an integer), Ruby will also throw an error. Instead, use Ruby’s built-in string interpolation (it’s cleaner and avoids type issues) or convert non-strings to strings with to_s.

Here’s the Fully Fixed Code

puts "What is your name?"
name = gets.chomp
puts "When were you born? Please enter your birthdate:"
birthdate = gets.chomp
puts "How old are you?"
age = gets.chomp.to_i
puts "Hello #{name}! Wow, that's a great day to be born—and that's a fantastic age!"
half_age = age / 2
puts "Half of your age is #{half_age}—that's fun to know!"

Quick Notes on the Improvements:

  • Used string interpolation (#{variable}) to seamlessly mix variables into strings without type errors
  • Added to_i to convert the age input to an integer for division
  • Cleaned up the output text to flow more naturally
  • Stored the half-age result in a separate variable for readability

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 07:49:22