M. Fall
M. Fall

Reputation: 1

Ruby issue: My "gets" function executes before my "puts" statement

I am learning Ruby and I tried a simple code:

system "clear"
print "What is your name?"
name = gets.chomp
puts name
puts "Hello #{ name.capitalize }, how are you?"

and the oupout is ready for the input without showing the print requested. then after I enter a string it show the print:

George
What is your name?George
Hello George, how are you?

Please help. I am confused. Thank you!

Upvotes: 0

Views: 256

Answers (2)

GorgonzolaTM
GorgonzolaTM

Reputation: 1

I just copied OP's code into my editor (VS Code) and I don't get what OP got. I got

What is your name?George
George
Hello George, how are you?

instead of

George
What is your name?George
Hello George, how are you?

Upvotes: 0

felixbuenemann
felixbuenemann

Reputation: 639

This is likely caused by output buffering and should be fixed by adding $stdout.sync = true before the first print statement.

Another solution is to call $stdout.flush to manually flush output after the print statement or replace print with puts (but that will add a newline).

Upvotes: 4

Related Questions