Create the loading three little dots

时间:2015-07-13 21:01:01

标签: ruby loading

Hello how can I make the three dot loading (...), so that it does something like this except without making a new line everytime:

Loading

Loading.

Loading...

Loading..

Loading.

and so on:

This is what I came up with, only problem is that I can't remove the dots one by one if loading continues for more than 1.5 seconds.

puts "Sending"
sleep(0.5)
print "."
sleep(0.5)
print "."
sleep(0.5)
print "."

Hopefully I am clear enough.

Thank you for your help.

2 个答案:

答案 0 :(得分:3)

10.times do |i|   
    print "Sending." +  ("." * (i % 3)) + "  \r"    
    $stdout.flush   
    sleep(0.5)
end

那么,这是如何工作的?

10.times do |i|   

重复以下代码10次,变量i表示当前迭代(0,1,2,3,4 ......)

    print "Sending." +  ("." * (i % 3)) + "  \r"

打印短语"发送。"接下来是几件事:

  • ("." * (i % 3))多次重复("倍增")字符串".",特别是i % 3,这是i的剩余时间{39} ; s除以3.因此当i为7时,i % 3为1。
  • "\r"将光标移回行的开头而不创建新行。如果你想到打字机,就像把马车(打字的那一位)归还给行的开头一样,这样你就可以再次输入同一行。这是回车

    $stdout.flush
    

确保打印数据。

    sleep(0.5)

睡眠半秒。

答案 1 :(得分:2)

You can try with $stdout.flush:

def loading number_of
  number_of.times do |t|
    print "Sending#{'.' * (t % 4)}   \r"
    $stdout.flush
    sleep 0.5
  end
end

Demonstration