Guest2
(Guest)
25 September 2008 14:05
1
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
···
--
Posted via http://www.ruby-forum.com/ .
TPReal
(TPReal)
25 September 2008 14:36
2
Li Chen wrote:
text[x, x+5]
You wanted either text[x..(x+5)] or better text[x,5]. Have a look at
String# .
TPR.
···
--
Posted via http://www.ruby-forum.com/\ .
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 .
···
--
Posted via http://www.ruby-forum.com/ .
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
···
On 25.09.2008, at 16:43, Lex Williams wrote:
Considering that :
a = "1112223334444"
watch the following irb session :
irb(main):010:0> a.scan(/((.)\2+)/).collect {|match| match[0]}
=> ["111", "222", "333", "4444"]
You'll miss the unrepeated characters:
> ruby -e 'p "abbcccdddd".scan(/((.)\2+)/).transpose.shift'
["bb", "ccc", "dddd"]
Where did "a" go?
Change the "+" into "*" and it'll work:
> ruby -e 'p "abbcccdddd".scan(/((.)\2*)/).transpose.shift'
["a", "bb", "ccc", "dddd"]
gegroet,
Erik V. - http://www.erikveen.dds.nl/