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

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.chomp to 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 need chomp—the to_i method automatically ignores any non-numeric characters (including newlines) when converting the input to an integer.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 08:33:00