Frank Frank - 1 year ago 67
Ruby Question

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

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. But instead the entire string is printed at once.

Answer Source

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 }