views:

101

answers:

4

I would like to brake a long word in my Ruby on Rails string (something like <wbr> in HTML). Is it possible to tell Ruby "add character x in string y each z characters"?

+1  A: 

In Perl it would be somewhere along the lines of s/(\w{42})/$1\n/g

Niels Castle
+8  A: 

Try

result = subject.gsub(/(.{10})/m, '\1XX')

substituting the number you want for 10 and the replacement string you want for XX

Tim Pietzcker
A: 

I'm not familiar with rails, but in pure ruby you can always write your own. No idea the amount of speed you give up for something like this if any.

def addcharacter(num, char, string)
 x = 0
 resultstring = ""
 string.each_byte do |byte|
   resultstring << byte.chr
   x += 1
   if x == num
   resultstring << char
   x = 0
   end

 end

   return resultstring
 end

 mystring = "hello there"

 a = addcharacter(2,"*",mystring)
 puts a
Beanish
Careful using `each_byte` for something like this. It only works when the characters are bytes i.e. ASCII. Weird behavior would ensue with UTF-* encoded strings.
BaroqueBobcat
A: 

If your original string is str = "0123456789abcde" and you want:

  • 01234XXX56789XXXabcdeXXX :: use str.gsub(/.{5}/, '\&XXX')
  • 01234XXX56789XXXabcde :: use str.scan(/.{5}/).join('XXX')

These will produce slightly different input for str = "012345678abcdef"

  • 01234XXX56789XXXabcdeXXXf :: from str.gsub(/.{5}/, '\&XXX')
  • 01234XXX56789XXXabcde :: from str.scan(/.{5}/).join('XXX')
  • 01234XXX56789XXXabcdeXXXfXXX :: from str.gsub(/.{1,5}/, '\&XXX')
  • 01234XXX56789XXXabcdeXXXf :: from str.scan(/.{1,5}/).join('XXX')
rampion