Skip to content

Instantly share code, notes, and snippets.

@kv109
Created October 25, 2010 13:01
Show Gist options
  • Save kv109/644908 to your computer and use it in GitHub Desktop.
Save kv109/644908 to your computer and use it in GitHub Desktop.
Using group_by on arrays
class Post
attr_reader :date, :text
def initialize(text)
@date = "2010-10-#{rand(2)+1}"
@text = text
end
end
posts = []
10.times do |t|
posts << Post.new("text no. #{t}")
end
posts_grouped_by_date = posts.group_by(&:date)
posts_grouped_by_date.keys #=>["2010-10-1", "2010-10-2"]
posts_grouped_by_date['2010-10-1'].size #=>3
posts_grouped_by_date['2010-10-2'].size #=>7
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment