tags:

views:

45

answers:

2

In a ruby string, how can I insert a space every X number of characters?

As an example, I'd like to insert a space every 8 characters of a given string.

+4  A: 
>> s = "1234567812345678123456781234567812345678"
=> "1234567812345678123456781234567812345678"
>> s.gsub(/(.{8})/, '\1 ')
=> "12345678 12345678 12345678 12345678 12345678 "

Edit: You could use positive lookahead to avoid adding an extra space at the end:

>> s.gsub(/(.{8})(?=.)/, '\1 \2')
=> "12345678 12345678 12345678 12345678 12345678"
Pär Wieslander
Close. What about every 8 characters, but don't add a space at the end of the string?
Shpigford
just add a `strip!`. so it would turn into `s.gsub(/(.{8})/, '\1 ').strip!`
Matt Briggs
What if the string initially had leading or trailing spaces?
Nabb
@Nabb: Then you could preprocess it w/ `s.gsub!(/^\s*|\s*$/,'')`
rampion
+3  A: 

Alternate solution:

s.scan(/.{1,8}/).join(' ')

String#scan will chunk it up for you (into spans of 8 characters - except for the last chunk, which may be shorter), and then Array#join will reunite the chunks with the appropriate character interspersed.

rampion