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 ...}
io_buffer.c
View on GitHub ↗
VALUE
rb_io_buffer_type_for(VALUE klass, VALUE string)
{
StringValue(string);
// If the string is frozen, both code paths are okay.
// If the string is not frozen, if a block is not given, it must be frozen.
if (rb_block_given_p()) {
struct io_buffer_for_yield_instance_arguments arguments = {
.klass = klass,
.string = string,
.instance = Qnil,
};
return rb_ensure(io_buffer_for_yield_instance, (VALUE)&arguments, io_buffer_for_yield_instance_ensure, (VALUE)&arguments);
}
else {
// This internally returns the source string if it's already frozen.
string = rb_str_tmp_frozen_acquire(string);
return io_buffer_for_make_instance(klass, string);
}
}
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