How to split string by x bytes?

I have big string.
I want to get array of parts of string (each 256 bytes).
What method is faster?

On Thu, Feb 10, 2011 at 3:39 PM, Yan B. [email protected] wrote:

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

string.scan /.{256}/

martin

On Thu, Feb 10, 2011 at 7:09 PM, Yan B. [email protected] wrote:

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

I don’t know if this is the fastest but…
You could try unpack.
Modify it the way you want.

str = “abcdefghijklmnopq”
p str.unpack(“a3”*(str.size/3))

Harry

Thanks!

Thanks! It is great :slight_smile:

Martin DeMello wrote in post #980786:

On Thu, Feb 10, 2011 at 3:39 PM, Yan B. [email protected] wrote:

I have big string.
I want to get array of parts of strings (each 256 bytes).
What method is faster?

string.scan /.{256}/

martin
Unpack is much faster. I have a string method which does something
similar

class String
def to_2d_array(value)
unpack(“a#{value}”*((size/value)+((size%value>0)?1:0)))
end
end

That enables me to do things like

string=“123456789”
str_array=(string*1000).to_2d_array(256)
str_array.size => 36
str_array[0].size => 256
str_array[-1].size => 40
(36-1)*256+40 => 9000

And in benchmarks:

require ‘benchmark’
Benchmark.measure { (“0”*10000000).scan(/.{256}/) } => 0.5700 0.0000
0.5700 (0.580)
Benchmark.measure { (“0”*10000000).unpack(“a”*256)} => 0.0000 0.0000
0.0000 (0.004)

Mac

Yeah! It is greate :smiley:

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs