Skip to content

End of Life Ruby 3.1 has reached end of life and gets no more fixes. Switch to Ruby 4.0 →

instance method

IO::Buffer#slice

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.

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

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

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 SLICE>
#  0x00000000  74 6f 73 74                                     tost

# ...and original string
string
# => tost
See also #size #to_s #set_value #transfer also in 4.1 · 4.0 · 3.4 · 3.3 · 3.2