From: Robert Klemme Date: 2010-09-21T18:08:36+09:00 Subject: Re: An elegant way... On Tue, Sep 21, 2010 at 11:00 AM, Robert Klemme wrote: > On Tue, Sep 21, 2010 at 10:38 AM, Brian Candler wrote: > > Fred, for the contrast here's my engineering approach.  It may not be > elegant (you decide) but you get modularity and reusability. > > First I'd start out with a proper representation.  If your numbers are > a central part of your application you may want to spend a class for > them: > > Num = Struct.new :pre, :val do >  def succ >    self.class.new pre, val.succ >  end > >  def to_s; "#{pre}#{val}" end >  def inspect; "#{self.class.name}(#{self})" end > >  include Comparable >  def <=>(o) to_a <=> o.to_a end > end > > def Num(s) >  %r{\A(\D*)(\d+)\z} =~ s or raise "bad arg %p" % s >  Num.new $1, $2.to_i > end > > Then we can set up a generic mechanism for this Forgot the end handling and mixed up two versions. Sorry for that. Here's the proper one module Enumerable def rangify(&bl) bl ||= lambda {|x, y| x == y ? x : (x..y)} res = [] a = b = nil each do |x| case when a.nil? a = b = x when x == b.succ b = x else res << bl[a, b] a = b = x end end res << bl[a, b] end end > Full story is here http://gist.github.com/589427 Cheers robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/