Skip to content

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

instance method

String#<<

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

Concatenates object to self and returns self:

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

If object is an Integer, the value is considered a codepoint and converted to a character before concatenation:

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

If that codepoint is not representable in the encoding of string, RangeError is raised.

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

If the encoding is US-ASCII and the codepoint is 0..0xff, string is automatically promoted to ASCII-8BIT.

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

Related: String#concat, which takes multiple arguments.

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