Reputation: 907
I have a block of code that looks like
runs.this_month.group_by(&:week).each do |week,runs|
puts 'week' + week
puts runs.size
end
Right now it just returns
week00
1
week 03
1
What I am hoping to have this loop generate is an object that has 0's if that week has no runs. For example, if I have the month of January, and there is one run the first week,no runs the second week, one run the 3rd week,and no runs the last week, ideally it would return something that looks like
[1,0,1,0]
I think my issue is with the group_by() enumerable not knowing how many weeks there are in a month for example.
Also FWIW the this_month scope looks for all runs
with :created_at this month. That bit works as expected and returns a group of all of the runs from this month.
edit1:
This is sloppy, but seems to be working:
month = [0,0,0,0]
weeks = [0,1,2,3]
runs.this_month.group_by(&:week).each do |week,runs|
if weeks.include? (week[0].to_i)
month[week.to_i] = runs
end
end
working means month looks like
[ActiveRecord...,0,ActiveRecord...,0]
Upvotes: 0
Views: 647
Reputation: 2558
I guess that weeks
are integers 0, 1, 2, 3.
default_stats = { 0: [], 1: [], 2: [], 3: [] }
runs.this_month.group_by(&:week).reverse_merge(default_stats)
Upvotes: 1