简体   繁体   中英

Gets.chomp() user input error in Ruby

So this is my code. It's pretty self-explanatory.

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."

My code output is as follows.

$  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.

It's probably a really simple error, but I would be grateful if you can point it out.

I take it that your question is: "All my prompts are printed all at once after all inputs. What's up with that?". I have an answer for you then :)

print doesn't add a newline to the string. And STDOUT doesn't flush until it's got a full line. Simple fix: replace print with puts (which does add newline char)

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."

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM