开发者

Just for fun, how do I write a ruby program that slowly prints to stdout one character at a time?

开发者 https://www.devze.com 2023-02-09 07:27 出处:网络
I thought this might work \"a b c d e f g h i j k\".each {|c| putc c ; sleep 0.25} I expected to see \"a b c d e f j\" be printed one character at a time with 0.25 seconds between each character.

I thought this might work

 "a b c d e f g h i j k".each {|c| putc c ; sleep 0.25}

I expected to see "a b c d e f j" be printed one character at a time with 0.25 seconds between each character. 开发者_JAVA技巧But instead the entire string is printed at once.


Two things:

  1. You need to use .each_char to iterate over the characters. In Ruby 1.8, String.each will go line-by-line. In Ruby 1.9, String.each is deprecated.
  2. You should manually flush $stdout if you want the chars to appear immediately. Otherwise, they tend to get buffered so that the characters appear all at once at the end.

.

#!/usr/bin/env ruby
"a b c d d e f g h i j k".each_char {|c| putc c ; sleep 0.25; $stdout.flush }


Two things:

  1. You need to split that string into an array before you use each on it.
  2. Turn off output buffering.

    $stdout.sync = true
    "a b c d d e f g h i j k".split(" ").each {|c| putc c ; sleep 0.25}
    


Ruby buffers output and will flush it to standard output after it reaches a certain size. You can force it to flush like so.

"a b c d e f g h i j k".each_char do |char|
   putc char
   $stdout.flush
   sleep 0.25
end

Note: if you don't want spaces between the characters when printed, use .split.each instead of .each_char.

Just for fun: with a definition like this:

def slowly
  yield.each_char { |c| putc c; $stdout.flush; sleep 0.25 }
end

You would be able to do this:

slowly do
  "a b c d e f g h i j k"
end


Try:

%w"a b c d e f g h i j k".each {|c| putc c ; sleep 0.25}

That works as is with Ruby 1.9.2, which doesn't need STDOUT to flush between each write.

If you want the intervening spaces remove %w and use each_char instead of each.


This is my way of "slow printing":

for i in "a b c d e f g h i j k".chars.to_a
  print i
  sleep 0.25
end
0

精彩评论

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

关注公众号