Simply replace things
and thing
with whatever large object you're iterating
over and put your iteration code in place of the code comment.
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.)