1. Technology
Send to a Friend via Email
You can opt-out at any time. Please refer to our privacy policy for contact information.

How Can I Use a Spinner Method in Ruby?

By

Question: How Can I Use a Spinner Method in Ruby?

Spinners give visual feedback that something is happening. If you have a task that takes more than a few seconds, a spinner could be a good idea. But how to implement a spinner on the console?

Answer:

The easiest way is to alternate a character between the /, -, \, and | characters. Doing this fast enough creates the illusion spinning. In order to get the characters to continually write to the same place on the screen, you simply have to print a backspace character.

This simple example will count from 0 to 9. Using \b in a string literal will print a backspace character, allowing you to print all the characters in the same place.


0.upto(9) do|i|
  print i
  sleep 0.5
  print "\b"
end
 

The next piece of this puzzle is how to run the time-consuming task at the same time as the spinner. To solve this, you can use a thread. Threads allow you to run more than one thing at a time. You can run the time-consuming task in a thread, and display the spinner as long as the thread is still "alive."


def spinner(code)
  chars = %w{ | / - \\ }
 
  t = Thread.new { code.call }
  while t.alive?
    print chars[0]
    sleep 0.1
    print "\b"
 
    chars.push chars.shift
  end
 
  t.join
end
 
  1. About.com
  2. Technology
  3. Ruby
  4. Tutorials
  5. FAQs
  6. How Can I Use a Spinner Method in Ruby?

©2014 About.com. All rights reserved.