Ruby中变量后打印的文本为何自动换行?
Fixing the Unwanted Newline Issue in Your Ruby Program
Hey there! Let's sort out that annoying extra newline you're seeing when your variables print. The root cause is super simple: the gets method captures everything you type, including the newline character (\n) that gets added when you press Enter. That's why when you use name later, it shoves the next text onto a new line.
Here's your revised code with the fix:
puts "Hey what's your name?!!" name = gets.chomp # Added .chomp to strip the trailing newline puts "OutputNAME: #{name}" puts "Hey #{name}! Howdy doin'!" puts "Tell us 2 numbers that add up to your age!" age1 = gets.to_i # No chomp needed here—to_i ignores newlines automatically age2 = gets.to_i puts "Hey! You're #{age1 + age2} years old! Gotcha!" puts "I'm totally new to Ruby on Rails, so thanks for running my first Ruby Program. Please do leave an upvote and I'll appreciate that." puts "If you think I need a downvote, please do state, in the comments section, what I could have done to make my program..."
Quick Explanations:
- For string inputs (like the user's name), always use
gets.chompto remove the hidden newline character. This keeps your interpolated text clean and on the same line. - For numeric inputs converted with
to_i, you don't needchomp—theto_imethod automatically ignores any non-numeric characters (including newlines) when converting the input to an integer.
内容的提问来源于stack exchange,提问作者user9585869
相关产品推荐
相关产品推荐

