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
2010-01-14 14:21:45
+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
2010-01-14 14:27:36
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
2010-01-14 15:25:32
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
2010-01-14 20:18:26
A:
If your original string is str = "0123456789abcde"
and you want:
01234XXX56789XXXabcdeXXX
:: usestr.gsub(/.{5}/, '\&XXX')
01234XXX56789XXXabcde
:: usestr.scan(/.{5}/).join('XXX')
These will produce slightly different input for str = "012345678abcdef"
01234XXX56789XXXabcdeXXXf
:: fromstr.gsub(/.{5}/, '\&XXX')
01234XXX56789XXXabcde
:: fromstr.scan(/.{5}/).join('XXX')
01234XXX56789XXXabcdeXXXfXXX
:: fromstr.gsub(/.{1,5}/, '\&XXX')
01234XXX56789XXXabcdeXXXf
:: fromstr.scan(/.{1,5}/).join('XXX')
rampion
2010-01-14 18:18:12