开发者

ruby multiple loop sets but with limited rows per set

Alrightie, so I'm building an CSV file thi开发者_如何转开发s time with ruby. The outer loop will run up to length of num_of_loops, but it runs for an entire set rather than up to the specified row. I want to change the first column of a CSV file to a new name for each row.

If I do this:

class_days = %w[Wednesday Thursday Friday]

num_of_loops = (num_of_loops / class_days.size).ceil

num_of_loops.times { 
   ["Wednesday","Thursday","Friday"].each do |x|
      data[0] = x
      data[4] = classname()

      # Write all to file
      #
      csv << data
   end
}

Then the loop will run only 3 times for a 5 row request.

I'd like it to run the full 5 rows such that instead of stopping at Wed/Thurs/Fri it goes to Wed/Thurs/Fri/Wed/Thurs instead.


class_days = %w[Wednesday Thursday Friday]
num_of_loops.times do |i|
  data[0] = class_days[i % class_days.size]
  data[4] = classname
  csv << data
end

The interesting part is here:

  class_days[i % class_days.size]

We need an index into class_days that is between 0 and class_days.size - 1. We can get that with the % (modulo) operator. That operator yields the remainder after dividing i by class_days.size. This table shows how it works:

i    i % 3
0      0
1      1
2      2
3      0
4      1
5      2
   ... 

The other key part is that the times method yields indices starting with 0.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜