Skip to content

Preview Ruby 4.1 is a preview. It can change before the final release. Switch to Ruby 4.0 →

class method

IO::Buffer.for

(::String) -> ::IO::Buffer
IO::Buffer.for(string) → readonly io_buffer
IO::Buffer.for(string) {|io_buffer| ... read/write io_buffer ...}

Creates a zero-copy IO::Buffer from the given string’s memory. Without a block, a frozen snapshot of the string is used as the buffer source, so later changes to the original string do not affect the buffer. When a block is provided, the buffer is associated directly with the string’s internal buffer and updating the buffer will update the string.

In the block form, the string is locked and cannot be modified while the block is executing.

If the string is frozen, it will create a read-only buffer which cannot be modified. If the string is shared, it may trigger a copy-on-write when using the block form.

Example
string = 'test'
buffer = IO::Buffer.for(string)
buffer.external? #=> true

buffer.get_string(0, 1)
# => "t"
string
# => "test"

buffer.resize(100)
# in `resize': Cannot resize external buffer! (IO::Buffer::AccessError)

IO::Buffer.for(string) do |buffer|
  buffer.set_string("T")
  string
  # => "Test"
end
See also .map .new also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1