class

String::Builder

Inherits IO / Reference / Object

Similar to IO::Memory, but optimized for building a single string.

You should never have to deal with this class. Instead, use String.build.

Constructors

new(capacity : Int = 64)
Source
new(string : String)
Source

Class methods

build(capacity : Int = 64, &) : String
Source

Instance methods

back(amount : Int) : Int32

Moves the write pointer, and the resulting string bytesize, by the given amount.

Source
buffer
Source
bytesize
Source
capacity
Source
chomp!(byte : UInt8) : self

Chomps the last byte from the string buffer. If the byte is '\n' and there's a '\r' before it, it is also removed.

Source
empty?
Source
read(slice : Bytes) : NoReturn

Reads at most slice.size bytes from this IO into slice. Returns the number of bytes read, which is 0 if and only if there is no more data to read (so checking for 0 is the way to detect end of file).

io = IO::Memory.new "hello"
slice = Bytes.new(4)
io.read(slice) # => 4
slice          # => Bytes[104, 101, 108, 108]
io.read(slice) # => 1
slice          # => Bytes[111, 101, 108, 108]
io.read(slice) # => 0
Source
set_encoding(encoding : String, invalid : Symbol | Nil = nil) : Nil

Sets the encoding of this IO.

The invalid argument can be:

  • nil: an exception is raised on invalid byte sequences
  • :skip: invalid byte sequences are ignored

String operations (gets, gets_to_end, read_char, <<, print, puts printf) will use this encoding.

Source
to_s

Returns a nicely readable and concise string representation of this object, typically intended for users.

This method should usually not be overridden. It delegates to #to_s(IO) which can be overridden for custom implementations.

Also see #inspect.

Source
write(slice : Bytes) : Nil

Writes the contents of slice into this IO.

io = IO::Memory.new
slice = Bytes.new(4) { |i| ('a'.ord + i).to_u8 }
io.write(slice)
io.to_s # => "abcd"
Source
write_byte(byte : UInt8) : Nil

Writes a single byte into this IO.

io = IO::Memory.new
io.write_byte 97_u8
io.to_s # => "a"
Source
write_string(slice : Bytes) : Nil

Writes the contents of slice, interpreted as a sequence of UTF-8 or ASCII characters, into this IO. The contents are transcoded into this IO's current encoding.

bytes = "你".to_slice # => Bytes[228, 189, 160]

io = IO::Memory.new
io.set_encoding("GB2312")
io.write_string(bytes)
io.to_slice # => Bytes[196, 227]

"你".encode("GB2312") # => Bytes[196, 227]
Source