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”