From: Josselin Date: 2007-08-22T15:54:59+09:00 Subject: Re: splitting Array - DRY On 2007-08-20 09:56:02 +0200, "Robert Klemme" said: > 2007/8/20, Josselin : >> On 2007-08-19 09:58:46 +0200, Stefan Rusterholz said: >> >>> Josselin wrote: >>>> I am presently splitting an array on 4 successives periods of time , is >>>> there a DRYest way to do it, or that's the way to go ? thanks >>>> >>>> @ads_id_w1 = advertisings.map {|ad| ad.id if ((ad.valid_until - >>>> ad.created_at) / 86400.0 <= 7)}.compact >>>> >>>> @ads_id_w2 = advertisings.map {|ad| ad.id if (((ad.valid_until - >>>> ad.created_at) / 86400.0 > 7) && ((ad.valid_until - ad.created_at) / >>>> 86400.0 <= 14)) }.compact >>>> >>>> @ads_id_w3 = advertisings.map {|ad| ad.id if (((ad.valid_until - >>>> ad.created_at) / 86400.0 > 14) && ((ad.valid_until - ad.created_at) / >>>> 86400.0 <= 21)) }.compact >>>> >>>> @ads_id_w4 = advertisings.map {|ad| ad.id if (((ad.valid_until - >>>> ad.created_at) / 86400.0 > 21) && ((ad.valid_until - ad.created_at) / >>>> 86400.0 <= 31)) }.compact >>> >>> class ClassOfAd >>> def week # may want to name it differently >>> return nil unless whateverdate.between?(acceptable_start, >>> acceptable_end) # your call here >>> ((ad.valid_until - ad.created_at).div(604800)) % 4 >>> end >>> @ads_id = Array.new(4) { [] } >>> advertisings.each {|ad| @ads_id[ad.week] = ad.id if ad.week } >>> >>> Depending on your needs that code can be condensed a bit more. >>> >>> Regards >>> Stefan >> >> thanks Stefan, I realize that, too frequently, I am programming Ruby as >> C .. not using the OO potential >> what's one of the best book about "Programming Ruby, the way it should >> be..." ? >> I need to practise outside my app dev >> >> note : also found that the 'week' has been already written.. : >> (ad.valid_until - ad.created_at) >= 2.weeks > > Basically you need a more generalized version of partition. Maybe > something like this works: > > @ads_id = advertisings.inject(Hash.new {|h,k| h[k]=[]}) do |h,ad| > h[(((ad.valid_until - ad.created_at) / 86400 - 1) / 7] << ad.id > h > end > > Note, I'm using interger arithmetic to reduce the number of result values. > > Kind regards > > robert Thanks Robert... I'll put it in my Personal Ruby Cookbook, that's DRYissimo !