Reputation: 485
I'm still quite new to ruby but have been stuck on this problem for half a day.
I have an array of dates in integer form (e.g. [1351136194, 1350142662, 1350118879]
) and I'm trying to turn it into an array containing the number of occurrences per day for the next 30 days.
Basically, I want to be able to query e.g. array[0]
for the number of dates within today's range, array[1]
for tomorrow etc.
Any help would be appreciated.
Upvotes: 2
Views: 240
Reputation: 5774
arr = [1351136194, 1350142662, 1350118879]
hash = {}
arr.each do |int_date|
date = Time.at(int_date).strftime("%d-%b-%Y")
hash.has_key?(date) ? hash[date] += 1 : hash[date] = 1
end
puts hash #{"25-Oct-2012"=>1, "13-Oct-2012"=>2}
Upvotes: 0
Reputation: 3376
Something like this should work. Basically you convert the times to dates, then group them so you can easily identify duplicates. Then create the array:
times = [1351136194, 1350142662, 1350118879]
dates = times.map{|t| Time.at(t).to_date}
occurences = dates.group_by{|d| d}
occurences_by_day = (Date.today..(Date.today + 30)).map{|d| occurences[d] ? occurences[d].size : 0}
Upvotes: 2