From: Michael Fellinger Date: 2009-03-02T21:26:12+09:00 Subject: Re: how to group visitors using hours On Mon, Mar 2, 2009 at 9:12 PM, Ayeye Brazov wrote: > 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. > -- > 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=> [#, #], 18=> [#, #], 13=>[#], 2=> [#, #], 9=>[#], 4=>[#], 10=>[#]} ^ manveru