Created
August 16, 2012 02:16
-
-
Save tkfm-yamaguchi/3365715 to your computer and use it in GitHub Desktop.
Set#classify
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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