Skip to content

End of Life Ruby 3.2 has reached end of life and gets no more fixes. 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 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 data 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.

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.3 · 3.1