how to wrap a long string

L

Li Chen

Hi all,

I need to wrap a long string into several small segments.
I search the forum and see a few solutions for that. I copy one script
and run it on my Vista(with very small change) and here are the output:


C:\Documents and Settings\chen73>irb
irb(main):001:0> text = 'aaaaa11111AAAAA22222BBBBB'
=> "aaaaa11111AAAAA22222BBBBB"
irb(main):002:0> 0.step(text.length, 5) {|x| puts text[x, x+5]}
aaaaa
11111AAAAA
AAAAA22222BBBBB
22222BBBBB
BBBBB

=> 0

It looks like the script really wraps the string. But it also repeats
printing out some stuff, such two times of 'AAAAA', '22222', 3 times of
'BBBBB'.
Is it possible to get the output as follows:

aaaaa
11111
AAAAA
22222
BBBBB

Thanks,

Li
 
L

Lex Williams

Considering that :

a = "1112223334444"

watch the following irb session :

irb(main):010:0> a.scan(/((.)\2+)/).collect {|match| match[0]}
=> ["111", "222", "333", "4444"]

using that regex , you'll obtain an array of matches .
 
K

Karl-Heinz Wild

Considering that :

a = "1112223334444"

watch the following irb session :

irb(main):010:0> a.scan(/((.)\2+)/).collect {|match| match[0]}
=> ["111", "222", "333", "4444"]

great idea!
... this will also match single letters / digits

irb(main):020:0> a = "11111122233344444445556667778888888AAABCCDEEEEF"
=> "11111122233344444445556667778888888AAABCCDEEEEF"
irb(main):021:0> puts a.scan( /((.)\2+|.)/ ).collect { |x| x[0] }
111111
222
333
4444444
555
666
777
8888888
AAA
B
CC
D
EEEE
F

regards
Karl-Heinz
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,821
Latest member
AleidaSchi

Latest Threads

Top