简体   繁体   中英

Ruby group_by return array

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]

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM