Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

stdout

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.

like image 471
Frank Avatar asked Feb 08 '11 01:02

Frank


People also ask

Which of the following functions prints one character at a time?

As we can see in the above program, it takes a single character at the run time from the user using the getchar() function. After getting the character, it prints the letter through the putchar() function.

How do you print on the same line in Ruby?

We can also use "\n" ( newline character ) to print a new line whenever we want as used in most of the programming languages.

Which command is used to add a newline to the end of the output in Ruby?

"\n" is newline, '\n\ is literally backslash and n.


1 Answers

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 }
like image 60
erjiang Avatar answered Sep 26 '22 19:09

erjiang