Ruby中的gets.chomp()用户输入错误

时间:2013-06-26 12:39:03

标签: ruby user-input

所以这是我的代码。这是非常不言自明的。

print "How old are you? "
age = gets.chomp()
print "How tall are you?"
height = gets.chomp()
print "How much do you weigh?"
weight = gets.chomp()
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."

我的代码输出如下。

$  C:/Ruby200/bin/ruby.exe ex11.rb
11
11
11
How old are you? How tall are you?How much do you weigh?So, you're 11 old, 11 tall and 11 heavy.

这可能是一个非常简单的错误,但如果你能指出它,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

我认为你的问题是:“我的所有提示都会在所有输入后立即打印出来。那是什么意思?”我有一个答案然后:)

print不会在字符串中添加换行符。 STDOUT在完成整行之前不会刷新。简单修复:将print替换为puts(确实添加了新行字符)

puts "How old are you? "
age = gets.chomp()
puts "How tall are you?"
height = gets.chomp()
puts "How much do you weigh?"
weight = gets.chomp()
puts "So, you're #{age} old, #{height} tall and #{weight} heavy."