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.
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.
>> 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"
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.