How to group visitors using hours

Hi,

I’ve got this problem, I have a Visitor class that keep tracks
of visitors. Each visitor has “created_at” field.
I’d like to group them by hours using “created_at”

I came up with this solution, but I’m not very happy about it…

First, I create a list having [“yy-mm-dd hh”,visitor.id], with

list = visitors.map{|i| [i.created_at.strftime("%Y-%m-%d %H"),

i.id]}

Then, I group each visitor depending on the hours using an Hash

hs= {}
for l in list
if hs.has_key?(l.first)
hs[l.first] << l.second # Use the hour as index, and append the
visitor id
else
hs[l.first] = [l.second]
end
end

The result is a Hash hs, and I can use it to get the visitors
given a certain hour.

However, I’m sure there’s a better way of doing it, especially if
I’d like to group visitors for “months” or “years”

Any suggestions please?!
thanks
b.

On Mon, Mar 2, 2009 at 9:12 PM, Ayeye B. [email protected]
wrote:

  list = visitors.map{|i| [i.created_at.strftime(“%Y-%m-%d %H”),     hs[l.first] = [l.second]
thanks
b.

Posted via http://www.ruby-forum.com/.

require ‘pp’

class Visitor
attr_accessor :created_at

def initialize(time)
@created_at = time
end
end

visitors = Array.new(10){ Visitor.new(Time.at(rand(2e9))) }

pp visitors.group_by{|v| v.created_at.hour }
{6=>
[#<Visitor:0xb7bc034c @created_at=Tue Jul 04 06:22:51 +0900 1978>,
#<Visitor:0xb7bc00a4 @created_at=Thu Jul 26 06:27:32 +0900 1979>],
18=>
[#<Visitor:0xb7bc0194 @created_at=Wed Jun 27 18:31:17 +0900 2018>,
#<Visitor:0xb7bbffdc @created_at=Sun Oct 03 18:37:50 +0900 1993>],
13=>[#<Visitor:0xb7bc0108 @created_at=Wed Feb 10 13:20:34 +0900 2027>],
2=>
[#<Visitor:0xb7bc0158 @created_at=Fri Jan 10 02:22:01 +0900 2003>,
#<Visitor:0xb7bc0054 @created_at=Sun May 30 02:15:58 +0900 1993>],
9=>[#<Visitor:0xb7bbff8c @created_at=Tue Oct 05 09:32:10 +0900 2032>],
4=>[#<Visitor:0xb7bc0388 @created_at=Mon May 01 04:03:29 +0900 2006>],
10=>[#<Visitor:0xb7bc002c @created_at=Mon Jun 27 10:28:29 +0900 1994>]}

^ manveru

Thanks for that!
b.