Reputation: 325
I am trying to implement a threads race in Ruby which should show each Thread progress in the terminal (kind of real-time). I got blocked with the point where I need to move to the previous terminal lines.
I use this solution atm:
bar, bar2 = '', ''
50.times do |i|
bar << '='
bar2 << '**'
puts "#{bar} - #{i+1}0%"
print "#{bar2} - #{i+1}0%"
print "\033[F\r"
sleep 0.3
end
still it is working only for 2 bars, and I have no idea how I can scale with some more threads.
Upvotes: 2
Views: 536
Reputation: 121020
One should extensively use escape sequences for cursor movement
:
BARS_COUNT = 3
SYMBOLS = %w|= ** ℹℹℹ|
BARS = ['', '', '']
BARS_COUNT.times { puts } # prepare the space
20.times do |i|
print "\033[#{BARS_COUNT}A"
BARS_COUNT.times do |pos|
BARS[pos] << SYMBOLS[pos]
puts "\033[#{i * SYMBOLS[pos].length}C#{SYMBOLS[pos]}"
end
sleep 0.1
end
For more sophisticated positioning use \033[<L>;<C>f
as described in the reference I linked.
Upvotes: 4