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.
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.
We can also use "\n" ( newline character ) to print a new line whenever we want as used in most of the programming languages.
"\n" is newline, '\n\ is literally backslash and n.
Two things:
.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.$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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With