views:

50

answers:

1

I'm trying to return an array of counted values for consecutive date ranges (that will vary in distance), so that I have something like the following:

counted_values = [2,0,4,5,6,0,0,4,2]

So far I've written something that works but makes me shudder slightly, as I'm sure there's a more Rubyist/Rails way of doing it.

Current code:

      startdate = @event.running_from
      enddate = @event.running_to
      totaltime = enddate - startdate
      timesegment = totaltime / 20
      segmentstart = startdate
      segmentend = startdate + timesegment
      @counted_values = []
      20.times {
        count = SignUp.count(:conditions => { :event_id => @event.id, :created_at => segmentstart..segmentend})
        @counted_values << count
        segmentstart = segmentend
        segmentend = segmentend + timesegment
      }

Can anyone help clean this up a bit?

+2  A: 

Maybe this construct would help you?

irb(main):253:0> (0..3).step 1.5 do |i|
irb(main):254:1*   puts i
irb(main):255:1> end
0
1.5
3.0
=> 0..3

Could look something like this:

  segmentlength = (enddate-startdate) / 20
  @counted_values = []
  (startdate...enddate).step segmentlength |start|{
    @counted_values << SignUp.count(:conditions => { :event_id => @event.id, :created_at => start..(start+segmentlength)})
  }
Styggentorsken