Reno
Reno

Reputation: 2982

Function to add line breaks to a string every so many characters?

Rails 2.3.5

I need a temp work around for a script that only has 1 possible styling. Is there a simple way to loop through a string and add line breaks? Like at every 80th character insert a '\n'? (really looping through a record set and doing this to a text field).

Thanks!

Upvotes: 3

Views: 4391

Answers (2)

Jake Dempsey
Jake Dempsey

Reputation: 6322

Here is another approach:

"hello".scan(/.{1}/).join("\n")

Upvotes: 3

Jake Dempsey
Jake Dempsey

Reputation: 6322

Not sure this is the best approach.. but you could use each_slice here. Maybe something like:

"SOME AWESOME STRING".chars.each_slice(80).map(&:join).join('\n')

Upvotes: 2

Related Questions