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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With