Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: Insert spaces every X number of characters

Tags:

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.

like image 487
Shpigford Avatar asked Jul 02 '10 18:07

Shpigford


1 Answers

>> 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" 
like image 153
Pär Wieslander Avatar answered Sep 19 '22 10:09

Pär Wieslander