Skip to content

Instantly share code, notes, and snippets.

@yalestar
Created February 6, 2012 22:46
Show Gist options
  • Save yalestar/1755636 to your computer and use it in GitHub Desktop.
Save yalestar/1755636 to your computer and use it in GitHub Desktop.
Find the longest streak of consecutive dates
dates = thing.order("created_at DESC").map(&:created_at)
longest = 1
streaks = []
return 0 if dates.nil? || dates.empty?
dates.each_with_index do |d, idx|
unless (idx == dates.size - 1)
d1 = dates[idx]
d2 = dates[idx + 1]
td = (d2-d1) / 1.day
if (0..1).include?(td) # start counting the streak
longest += 1
else
# add that streak to the list and reset it
streaks << longest
longest = 0
end
end
end
streaks.uniq.max || 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment