Skip to content
instance method

IO::Buffer#slice

(::Integer offset, ::Integer length) -> ::IO::Buffer
slice([offset, [length]]) → io_buffer

Produce another IO::Buffer which is a slice (or view into) the current one starting at offset bytes and going for length bytes.

The slicing happens without copying of memory, and the slice keeps being associated with the original buffer’s source (string, or file), if any.

If the offset is not given, it will be zero. If the offset is negative, it will raise an ArgumentError.

If the length is not given, the slice will be as long as the original buffer minus the specified offset. If the length is negative, it will raise an ArgumentError.

Raises RuntimeError if the offset+length is out of the current buffer’s bounds.

Example
string = 'test'
buffer = IO::Buffer.for(string).dup

slice = buffer.slice
# =>
# #<IO::Buffer 0x0000000108338e68+4 SLICE>
# 0x00000000  74 65 73 74                                     test

buffer.slice(2)
# =>
# #<IO::Buffer 0x0000000108338e6a+2 SLICE>
# 0x00000000  73 74                                           st

slice = buffer.slice(1, 2)
# =>
# #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE>
# 0x00000000  65 73                                           es

# Put "o" into 0s position of the slice
slice.set_string('o', 0)
slice
# =>
# #<IO::Buffer 0x00007fc3d34ebc49+2 SLICE>
# 0x00000000  6f 73                                           os

# it is also visible at position 1 of the original buffer
buffer
# =>
# #<IO::Buffer 0x00007fc3d31e2d80+4 INTERNAL>
# 0x00000000  74 6f 73 74                                     tost
See also #size #to_s #shared? #transfer also in 4.1 · 3.4 · 3.3 · 3.2 · 3.1