How to split string by x bytes?

Y

Yan Bernacki

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

Yan Bernacki

Now I have this:

packets = (data.size.to_f / 256).ceil
packets.times do |packet|
socket.write data[packet..(packet+256)]
end

And this is very ugly :(
 
H

Harry Kakueki

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
 
P

Paul Mckibbin

Martin DeMello wrote in post #980786:
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
Mac
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,611
Members
45,281
Latest member
Pedroaciny

Latest Threads

Top