On Wed, 25 Oct 2006 05:40:51 -0700, "anthony.green wrote:

> Can someone offer an explaination as to what I'm encountering here..
> 
> ......................................................................................
> This code doesn't work...
> 
> class Time
>   def <=>(other_time)
>     self.strftime("%H%M%S%Y%m%d").to_i <=>
> other_time.strftime("%H%M%S%Y%m%d").to_i
>   end
> end
> 
> first = Time.local(2006, 10, 21)
> last = Time.local(2006, 10, 27)
> 
> time_slots = []
> range = first..last
> range.step(1.hour) do |day_slot|
>   time_slots << day_slot
> end
> 
> time_slots.sort
> 
> ......................................................................................
> 
> the time_slots array isn't populating properly
> ......................................................................................
> 
> This does
> 
> first = Time.local(2006, 10, 21)
> last = Time.local(2006, 10, 27)
> 
> time_slots = []
> range = first..last
> range.step(1.hour) do |day_slot|
>   time_slots << day_slot
> end
> 
> class Time
>   def <=>(other_time)
>     self.strftime("%H%M%S%Y%m%d").to_i <=>
> other_time.strftime("%H%M%S%Y%m%d").to_i
>   end
> end
> 
> time_slots.sort

You can use a custom comparison function by passing a block to sort, so
there's no reason to override the spaceship operator (that is, the <=>
operator).

You could use time_slots.sort {|x,y| x.strftime("%H%M%S%Y%m%d").to_i \
<=> y.strftime("%H%M%S%Y%m%d").to_i}

It's probably more efficient to use sort_by, as that only computes each
strftime once:

time_slots.sort_by{|x| x.strftime("%H%M%S%Y%m%d").to_i }

--Ken

-- 
Ken Bloom. PhD candidate. Linguistic Cognition Laboratory.
Department of Computer Science. Illinois Institute of Technology.
http://www.iit.edu/~kbloom1/
I've added a signing subkey to my GPG key. Please update your keyring.