tags:

views:

228

answers:

3

I'm trying to split a sizeable string every four characters. This is how I'm trying to do it:

big_string.split(/..../)

This is yielding a nil array. As far as I can see, this should be working. It even does when I plug it into an online ruby regex test.

A: 

Hmm, I don't know what Rubular is doing there and why - but

big_string.split(\....\)

does translate into

split the string at every 4-character-sequence

which should correctly result into something like

["", "", "", "abc"]
Marcel J.
+15  A: 

Try scan instead:

$ irb
>> "abcd1234beefcake".scan(/..../)
=> ["abcd", "1234", "beef", "cake"]

or

>> "abcd1234beefcake".scan(/.{4}/)
=> ["abcd", "1234", "beef", "cake"]

If the number of characters isn't divisible by 4, you can also grab the remaining characters:

>> "abcd1234beefcakexyz".scan(/.{1,4}/)
=> ["abcd", "1234", "beef", "cake", "xyz"]

(The {1,4} will greedily grab between 1 and 4 characters)

Ryan McGeary
yep, scan was it :)
deeb
A: 

Whoops.

str = 'asdfasdfasdf'
c = 0; out = []; inum = 4
(str.length/inum).round.times do |s|
out.push(str[c,round(s*inum)])
c += inum
end
CodeJoust