Skip to content

Instantly share code, notes, and snippets.

@ericboehs
Last active March 10, 2022 12:43
Show Gist options
  • Save ericboehs/6184fc970a00549904df to your computer and use it in GitHub Desktop.
Save ericboehs/6184fc970a00549904df to your computer and use it in GitHub Desktop.
Easy way to display progress in command line ruby script

Usage

Simply replace things and thing with whatever large object you're iterating over and put your iteration code in place of the code comment.

Explanation

In ruby you can append with_index and an index variable to your enumerators and it will give you an iterator counter (i). Using this we calculate a progress precentage:

(i.to_f / things.length * 100).to_i

This is the simplest/shortest way I know in ruby to get a whole number percentage.

There's also a spinner which is done via line 2 and line 6. The replacement is done by printing a bunch (16) of backspace characters (\b) followed by the current progress and the spinner on every iteration. Using ruby's Array.rotate!, we get the next character in the spinner and print that.

And if you're new to ruby, multiplying a string by an integer ("\b" * 16) just prints the string 16 times. You may also be unfamiliar with print, which is just like puts but doesn't print a new line, and giving print arguments. In print, multiple arguments is basically the same thing as concatenating the string via +. This just gives me a slightly shorter syntax. (Multiple arguments to puts would print each argument on a new line.)

puts "Importing #{things.length} things..."
pinwheel = %w{ | / - \\ }
things.each.with_index do |thing, i|
percentage = (i.to_f / things.length * 100).to_i
print "\b" * 16, "Progress: #{percentage}% ", pinwheel.rotate!.first
# Iterator code...
end
puts 'Done.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment