Skip to content

Instantly share code, notes, and snippets.

@tkfm-yamaguchi
Created August 16, 2012 02:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tkfm-yamaguchi/3365715 to your computer and use it in GitHub Desktop.
Save tkfm-yamaguchi/3365715 to your computer and use it in GitHub Desktop.
Set#classify
#!/usr/bin/env ruby
# coding:utf-8
# = Summary:
#
# Set#classify Example.
#
# Returns Hash instance whose key is date, and value is the set object
# consist from date instances within from date_range's first date to
# date_range's last date.
#
require 'date'
require 'set'
require 'pp'
# Set [START_DATE END_DATE]
date_range = %w[2012-08-01 2012-08-31]
Date.class_eval do
def to_sdate
Date::DAYNAMES[wday]
end
end
# Make all target dates
dates = Range.new(*date_range.map(&Date.method(:parse))).to_a
# Main
pp Set.new(dates).classify(&:to_sdate)
# code which is not using Set#classify:
# NOTE: returned hash's values are instance of Array
# while values are instance of Set using Set#classify.
#from_normal = dates.inject({}){|memo, d| memo.key?(d.to_sdate) ? memo[d.to_sdate] << d : memo[d.to_sdate] = [d]; memo }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment