On Tue, Sep 21, 2010 at 11:00 AM, Robert Klemme
<shortcutter / googlemail.com> wrote:
> On Tue, Sep 21, 2010 at 10:38 AM, Brian Candler <b.candler / pobox.com> wro=
te:
>
> Fred, for the contrast here's my engineering approach. =A0It may not be
> elegant (you decide) but you get modularity and reusability.
>
> First I'd start out with a proper representation. =A0If your numbers are
> a central part of your application you may want to spend a class for
> them:
>
> Num =3D Struct.new :pre, :val do
> =A0def succ
> =A0 =A0self.class.new pre, val.succ
> =A0end
>
> =A0def to_s; "#{pre}#{val}" end
> =A0def inspect; "#{self.class.name}(#{self})" end
>
> =A0include Comparable
> =A0def <=3D>(o) to_a <=3D> o.to_a end
> end
>
> def Num(s)
> =A0%r{\A(\D*)(\d+)\z} =3D~ s or raise "bad arg %p" % s
> =A0Num.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 ||=3D lambda {|x, y| x =3D=3D y ? x : (x..y)}

    res =3D []
    a =3D b =3D nil

    each do |x|
      case
      when a.nil?
        a =3D b =3D x
      when x =3D=3D b.succ
        b =3D x
      else
        res << bl[a, b]
        a =3D b =3D x
      end
    end

    res << bl[a, b]
  end
end

> Full story is here http://gist.github.com/589427

Cheers

robert

--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/