0

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]

5
  • The group_by is certainly part of your problem. What have you tried to resolve that issue? Simplest way would be to just add empty entries for the weeks that are missing. Commented Jan 23, 2015 at 22:39
  • @NickVeys- I have tried checking the value of "week" (00 or 03 in this case) against an array of [0,1,2,3] to see if that week belongs there, if so put the run in that element's position...if that makes sense Commented Jan 23, 2015 at 22:42
  • Ok, did that help? The code you posted just prints things. It's confusing because you are asking for something when it looks like your code doesn't even attempt to do it. You get much better responses on this site if you try but fail, and then ask for help with your current solution. Commented Jan 23, 2015 at 22:46
  • 1
    Yeah code doesn't work well in comments, just edit your question. Commented Jan 23, 2015 at 22:47
  • yup, sorry about that. Should have formatted my question more clearly. The edit has a bit more clarification Commented Jan 23, 2015 at 22:50

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.