是的,這適用於Windows,Mac OS X和Linux。提高由Niklas'的建議,可以讓這個更一般像這樣:
def show_wait_spinner(fps=10)
chars = %w[|/- \\]
delay = 1.0/fps
iter = 0
spinner = Thread.new do
while iter do # Keep spinning until told otherwise
print chars[(iter+=1) % chars.length]
sleep delay
print "\b"
end
end
yield.tap{ # After yielding to the block, save the return value
iter = false # Tell the thread to exit, cleaning up after itself…
spinner.join # …and wait for it to do so.
} # Use the block's return value as the method's
end
print "Doing something tricky..."
show_wait_spinner{
sleep rand(4)+2 # Simulate a task taking an unknown amount of time
}
puts "Done!"
:
def show_wait_cursor(seconds,fps=10)
chars = %w[|/- \\]
delay = 1.0/fps
(seconds*fps).round.times{ |i|
print chars[i % chars.length]
sleep delay
print "\b"
}
end
show_wait_cursor(3)
如果你不知道這個過程會有多長時間,你可以在另一個線程這樣做這一次輸出:從彼得
Doing something tricky...|
Doing something tricky.../
Doing something tricky...-
Doing something tricky...\
(et cetera)
Doing something tricky...done!
這將在所有重要的操作系統工作,我知道的,除非打印字符發生導致換行。 – 2012-04-21 19:28:22
適用於Linux,Ruby 1.8.7 ... – 2012-04-21 19:28:24
順便說一下,這相當於'('/ - \\ |'* 10).each {| c |打印c;睡眠(0.1);打印「\ b」}' – 2012-04-21 19:30:31