[英]How to make delay before each character is printed in a string using Ruby
Does anyone know how to create a small delay (perhaps 0.1 seconds) between the printing of each character in a string in Ruby? 有谁知道如何在Ruby中在字符串中的每个字符打印之间创建一个小的延迟(可能为0.1秒)?
I have tried some other methods (shown below); 我尝试了其他方法(如下所示); however, I'm certain that a simpler method exists as the method im using is time (and space) consuming:
但是,我确定存在一个更简单的方法,因为im使用的方法很耗时间(和空间):
#ugly/boring method vvv
print "h"
sleep 0.1
print "e"
sleep 0.1
print "l"
sleep 0.1
print "l"
sleep 0.1
print "o"
I have done some research on the topic and found a method under C and php but no one seems to have an answer for Ruby. 我已经对该主题进行了一些研究,并发现了在C和php下的一种方法,但是似乎没人能找到Ruby的答案。
Thanks in advance for the help. 先谢谢您的帮助。
"hello".each_char do |c|
sleep 0.1
print c
end
Docs: String#each_char 文件: String#each_char
You could also monkey-patch the string class: 您还可以猴子修补字符串类:
class String
def print_slowly
self.each_char do |c|
sleep 0.1
print c
end
end
end
#usage
"hello".print_slowly
A super simple approach would be something like this: 一个超级简单的方法是这样的:
"hello".split(//).each do |c|
sleep 0.1
print c
end
Here's a more verbose explanation: 这是更详细的解释:
string = "hello"
split_that_string = string.split(//);
for character in split_that_string
sleep 0.1
print character
end
You could also make a method for it: 您也可以为此创建一个方法:
def print_a_string_one_character_at_a_time(string)
array_of_characters = string.split(//);
for character in array_of_characters
sleep 0.1
print character
end
end
and then you can pass any string to that method. 然后您可以将任何字符串传递给该方法。 Here's an example:
这是一个例子:
print_a_string_one_character_at_a_time("Hello, World!")
That will type out Hello, World! 这将输入Hello,World! one character at a time (and return the array of characters).
一次一个字符(并返回字符数组)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.