Skip to content

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

instance method · added in Ruby 3.4

String#append_as_bytes

(*::String | ::Integer) -> ::String
append_as_bytes(*objects) → self

Concatenates each object in objects into self; returns self; performs no encoding validation or conversion:

Example
s = 'foo'
s.append_as_bytes(" \xE2\x82") # => "foo \xE2\x82"
s.valid_encoding?              # => false
s.append_as_bytes("\xAC 12")
s.valid_encoding?              # => true

When a given object is an integer, the value is considered an 8-bit byte; if the integer occupies more than one byte (i.e,. is greater than 255), appends only the low-order byte (similar to String#setbyte):

Example
s = ""
s.append_as_bytes(0, 257) # => "\u0000\u0001"
s.bytesize                # => 2

Related: see Modifying.

Ruby version changes

  1. 3.4
    • String#append_as_bytes was added to more easily and efficiently work with binary buffers and protocols. It directly concatenate the arguments into the string without any encoding validation or conversion. [Feature #20594]

See also #[]= #ascii_only? #[] #b also in 4.0 · 3.4