开发者

Program running not in order

开发者 https://www.devze.com 2023-03-18 13:05 出处:网络
I tried running this simple code: puts 4 i = gets puts i It\'s \"working\", but the console asks for a string and just 开发者_运维技巧then it prints 4 and iAdd a flush call before gets:

I tried running this simple code:

puts 4
i = gets
puts i

It's "working", but the console asks for a string and just 开发者_运维技巧then it prints 4 and i


Add a flush call before gets:

$stdout.flush


Instead of explicitly calling $stdout.flush:

$stdout.sync = true


Works in order for me using ruby 1.8.7, 1.9.2 and ree. What version of ruby and operating system are you on?


What are you hoping to accomplish here ? Normally the interpreter gathers all data before presenting you with the output. It's simply isnt bash :)


I guess you may be hit by output buffering. But your code example does not show how the program might "ask" for input, so I guess that you type answer just before ruby starts. Then your ruby program reads the input from input buffers, as the data is not read directly from the keyboard.

Are you sure that your problem is caused by exactly this code you have shown us?

Usually problems with data shown on terminal in wrong order are caused by using two different output streams: STDIN and STDERR for example. Each stream may decide to flush its data at different times.

if you want to make sure the text is displayed before something happens (as in this example) use the 'flush' command, as Yossi suggests.

0

精彩评论

暂无评论...
验证码 换一张
取 消