Ruby中无法对用户输入的年龄字符串执行除法运算求助
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_ito 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

