2

I have an Rails 4 application that collects attendance at church services. Some weeks there are two services and some weeks there is only one. I need to get the total attendance for each week and show it as a graph.

By calling:

Stat.calculate(:sum, :attendance, group: :date)

in the console I have been able to collect the data in a hash like this:

{Sun, 06 Jan 2013=>66, Sun, 13 Jan 2013=>65, Sun, 20 Jan 2013=>60, Sun, 27 Jan 2013=>67, Sun, 03 Feb 2013=>60, Sun, 10 Feb 2013=>76, Sun, 17 Feb 2013=>65, Sun, 24 Feb 2013=>52, Sun, 03 Mar 2013=>52, Sun, 10 Mar 2013=>45, Sun, 17 Mar 2013=>56, Sun, 24 Mar 2013=>134, Sun, 31 Mar 2013=>76, Sun, 07 Apr 2013=>88, Sun, 14 Apr 2013=>87, Sun, 28 Apr 2013=>93, Sun, 05 May 2013=>93, Sun, 12 May 2013=>95, Sun, 19 May 2013=>90, Sun, 26 May 2013=>87, Sun, 02 Jun 2013=>71, Sun, 09 Jun 2013=>86, Sun, 16 Jun 2013=>109, Sun, 23 Jun 2013=>80, Sun, 30 Jun 2013=>68, Sun, 07 Jul 2013=>75, Sun, 14 Jul 2013=>73}

But What I need for my chart is an array of hashes in the form of:

{date: "Sun, 23 Jun 2013", attendance: 80}, {date: "Sun, 30 Jun 2013", attendance: 68"}

So I am trying to figure out how to convert the first form into the second form.

I'm sure its something pretty easy, but my limited rails knowledge is hitting a wall.

2 Answers 2

5
.collect{|key,value| {:date => key, :attendance => value} }

loop through and create a new hash where the original key becomes the value for date and the original value becomes the value for attendance. These new hashes are collected into an array.

Sign up to request clarification or add additional context in comments.

1 Comment

I agree. I used the first answer prior to seeing Shawn's response. I've refactored to this.
2

You can think as below:

h = {"Sun, 06 Jan 2013"=>66, "Sun, 13 Jan 2013"=>65, "Sun, 20 Jan 2013"=>60 }
h.map{|k,v| Hash[:date,k,:attend,v]}
# => [{:date=>"Sun, 06 Jan 2013", :attend=>66},
#     {:date=>"Sun, 13 Jan 2013", :attend=>65},
#     {:date=>"Sun, 20 Jan 2013", :attend=>60}]

3 Comments

@NielsB. made it readble... :) Ready for all challenges.. :)))
That is better, but I still prefers Shawns answer because it reads well and only requires you to know the collect/map method. Your example also requires you to know the counter intuitive [] class method from the Hash class.
@NielsB. I have no issue... I liked my one, I use Kernel#Hash instead of {}.. simple.. :))) But thanks for throwing your comment.. :) I like feedbacks...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.