Skip to content

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

instance method

String#<<

(::string | ::Integer str_or_codepoint) -> self
self << object → self

Appends a string representation of object to self; returns self.

If object is a string, appends it to self:

Example
s = 'foo'
s << 'bar' # => "foobar"
s          # => "foobar"

If object is an integer, its value is considered a codepoint; converts the value to a character before concatenating:

Example
s = 'foo'
s << 33 # => "foo!"

Additionally, if the codepoint is in range 0..0xff and the encoding of self is Encoding::US_ASCII, changes the encoding to Encoding::ASCII_8BIT:

Example
s = 'foo'.encode(Encoding::US_ASCII)
s.encoding # => #<Encoding:US-ASCII>
s << 0xff  # => "foo\xFF"
s.encoding # => #<Encoding:BINARY (ASCII-8BIT)>

Raises RangeError if that codepoint is not representable in the encoding of self:

Example
s = 'foo'
s.encoding              # => <Encoding:UTF-8>
s << 0x00110000         # 1114112 out of char range (RangeError)
s = 'foo'.encode(Encoding::EUC_JP)
s << 0x00800080         # invalid codepoint 0x800080 in EUC-JP (RangeError)

Related: see Modifying.

See also #-@ #<=> #+@ #== also in 4.0 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0