Home > Mobile >  Show message every x percent iterations Ruby
Show message every x percent iterations Ruby

Time:02-02

I want my code to show a message every 20% of items processed. I am not very happy with the way I am doing. I am sure have a smarter way

The way I am doing:

count = 0
size = foo.get_items_size (items)
target = 20
loop all items
   items_processed = count*100 / size
   if items_processed == target
      puts "#{items_processed}% items"
      target  = 20
   end
   count  =1
end



CodePudding user response:

I would use Enumerable#each.with_index in combination with of only printing the output when the current index is a multiple of 20:

STEPS = 20

items.each.with_index(1) do |item, index|
  # do stuff with item

  puts "#{index}% items processes" if index.modulo(STEPS).zero?
end

CodePudding user response:

Check if the below code is helpful:

items = 1..100
target_percent = 20
step = ((target_percent/100.0) * items.size).round

items.each.with_index(1) do |item, index|
  # Some other working logic
  puts "#{index}% of work done!" if index.modulo(step).zero?
end

Since I don't know what's in the item list, I have just considered it as an array. This will also work if you wish to change the target_percent.

CodePudding user response:

You could incorporate the counter into your loop via with_index and make your code a little more robust by comparing the current percentage to your target via >= rather than ==:

items = ('A'..'M').to_a
target = 20

items.each.with_index(1) do |item, index|
  puts item # process item

  if index.quo(items.size) >= target.quo(100)
    puts "#{target}% processed"
    target  = 20
  end
end

This will print 20%, 40%, 60% etc. whenever exceeding that percentage:

A
B
C
20% processed
D
E
F
40% processed
G
H
60% processed
I
J
K
80% processed
L
M
100% processed

Note that the actual percentages are 23%, 46%, 62%, and 85%.

  •  Tags:  
  • ruby
  • Related