Skip to content

Maintenance Ruby 3.3 gets fixes, but no new features. Switch to Ruby 4.0 →

class method

IO::Buffer.for

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 internal copy of the string is created efficiently and used as the buffer source. When a block is provided, the buffer is associated directly with the string’s internal buffer and updating the buffer will update the string.

Until free is invoked on the buffer, either explicitly or via the garbage collector, the source string will be locked and cannot be modified.

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
# => "best"

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.1 · 4.0 · 3.4 · 3.2 · 3.1