Chop a string in Ruby into fixed length string ignoring (not considering/regardless) new line or space characters
"This is some\nText\nThis is some text".scan(/.{1,17}/m)
# => ["This is some\nText", "\nThis is some tex", "t"]
Yet another way:
(0..(a.length / 17)).map{|i| a[i * 17,17] }
#=> ["This is some\nText", "\nThis is some tex", "t"]
Update
And benchmarking:
require 'benchmark'
a = "This is some\nText\nThis is some text" * 1000
n = 100
Benchmark.bm do |x|
x.report("slice") { n.times do ; (0..(a.length / 17)).map{|i| a[i * 17,17] } ; end}
x.report("regex") { n.times do ; a.scan(/.{1,17}/m) ; end}
x.report("eachc") { n.times do ; a.each_char.each_slice(17).map(&:join) ; end }
end
result:
user system total real
slice 0.090000 0.000000 0.090000 ( 0.091065)
regex 0.230000 0.000000 0.230000 ( 0.233831)
eachc 1.420000 0.010000 1.430000 ( 1.442033)