Collapsing array output

I recall discussion of something similar a while ago, but I cannot
find it…

I would like to consolidate the output of some arrays containing
sequences of (string) numbers like,

3, 4, 5, 8, 10, 11, 15, 17

to an output like,

3-5, 8, 10-11, 15, 17

Can someone point me in the right direction?

Thanks,

···


Bil

“Bil Kleb” W.L.Kleb@larc.nasa.gov wrote in message
news:3D27DCC3.27D53F3D@LaRC.NASA.Gov

I recall discussion of something similar a while ago, but I cannot
find it…

I would like to consolidate the output of some arrays containing
sequences of (string) numbers like,

3, 4, 5, 8, 10, 11, 15, 17

to an output like,

3-5, 8, 10-11, 15, 17

Can someone point me in the right direction?

My first try:

···

a = 3, 4, 5, 8, 10, 11, 15, 17
b =
first = 0
while first<a.length
last = first+1
last += 1 while last<a.length && Range.new(a[first],a[last]).to_a ==
a[first…last]
b << ( (first==last-1) ? “#{a[first]}” : “#{a[first]}-#{a[last-1]}” )
first = last
end
puts b.join(', ')

Thanks,

Bil

Park Heesob

I recall discussion of something similar a while ago, but I cannot
find it...

[ruby-talk:31789]

Guy Decoux

Hi –

···

On Sun, 7 Jul 2002, Bil Kleb wrote:

I recall discussion of something similar a while ago, but I cannot
find it…

I would like to consolidate the output of some arrays containing
sequences of (string) numbers like,

3, 4, 5, 8, 10, 11, 15, 17

to an output like,

3-5, 8, 10-11, 15, 17

Can someone point me in the right direction?

This was the subject of a little coding puzzle/challenge. At
http://www.rubygarden.org/ruby?CodingChallenge0001 you’ll find a
bunch of solutions.

(Anyone want to create a CodingChallenge0002? :slight_smile:

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav

David Alan Black wrote:

This was the subject of a little coding puzzle/challenge. At
http://www.rubygarden.org/ruby?CodingChallenge0001 you’ll find a
bunch of solutions.

That’s it! Thanks.

Nitpick question: on the opening page you use the identation-allowing
form of the here document, <<-EOE, but you do not indent the terminating EOE?

···


Bil

Hi –

···

On Sun, 7 Jul 2002, Bil Kleb wrote:

David Alan Black wrote:

This was the subject of a little coding puzzle/challenge. At
http://www.rubygarden.org/ruby?CodingChallenge0001 you’ll find a
bunch of solutions.

That’s it! Thanks.

Nitpick question: on the opening page you use the identation-allowing
form of the here document, <<-EOE, but you do not indent the terminating EOE?

Personally I tend to use the <<-EOE syntax pretty much automatically.
For one thing, it means that things still work if the whole thing gets
indented – for example, indenting code for clarity in a message on
this list.

David


David Alan Black
home: dblack@candle.superlink.net
work: blackdav@shu.edu
Web: http://pirate.shu.edu/~blackdav