carriwitchet
carriwitchet

Reputation: 121

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.

Upvotes: 0

Views: 1038

Answers (1)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230296

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

Upvotes: 1

Related Questions