【问题标题】:Ruby sleep(0.05) each character, on all outputsRuby sleep(0.05) 每个字符,在所有输出上
【发布时间】:2015-11-19 23:51:57
【问题描述】:

有没有可能达到和这个一样的效果:

"Hello World".each_char do |c| 
  print c; 
  sleep(0.05) 
end

在终端输出上?我认为必须有一种更简单/更简洁的方法来执行此操作,而不是将上面的代码添加到每个字符串的末尾,然后在每个字符串之后添加新行。

【问题讨论】:

    标签: ruby terminal output sleep


    【解决方案1】:

    将其定义为方法:

    def slow_print(string)
      string.each_char { |c| print c; sleep(0.05) }
    end
    

    然后调用它:

     slow_print("Hello World")
    

    【讨论】:

    • 我明白了,但是你知道有没有办法告诉 Ruby 一次所有的字符串都应该像这样打印?我试过重新定义类 String
    • @Oscar 你现在用什么方法打印字符串,puts
    • @Oleander 是的,就是这样。是不是我需要重新定义 String 类中的 puts 方法?
    • @Oscar putsKernel 类上定义。 See this link.
    猜你喜欢
    • 2011-03-27
    • 2020-07-21
    • 2013-08-31
    • 1970-01-01
    • 2011-01-05
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 2019-10-17
    相关资源
    最近更新 更多