From: Brian Candler Date: 2009-12-17T01:24:21+09:00 Subject: Re: Using threads to show progress Aldric Giacomoni wrote: >>if __FILE__ == $0 >> Progress << "Feeding the cat" >> 33.times do |x| >> Progress << ["munch", x, 33] >> sleep(0.1) >> end >> Progress << "Put the cat out" >> Progress << "Go to sleep" >> 20.times do |x| >> Progress << ["zzzzzzz", x, 20] >> sleep(0.2) >> end >> Progress << "Wakey wakey!" >>end > > From inside a loop, can I dynamically know over how many elements the > loop will iterate? I noticed the repetition of '33' and '20' ... :) It depends on what you're iterating over. If it's an Array, use Array#size: myarray.each_with_index do |elem, i| Progress << ["Processing", i, myarray.size] ... end Progress does here assume that you know the number of iterations in advance (so it can show a progress bar). You could easily modify the code so that Progress << ["munch", x] it would just display the number x, rather than a bar. def bar(category, n, m=nil) if m @out << sprintf("%-20s[%-56s]", category, "*" * (56.0 * n / m)) else @out << sprintf("%-20s %-56s", category, n.to_s) end end -- Posted via http://www.ruby-forum.com/.