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
string.c
View on GitHub ↗
VALUE
rb_str_concat(VALUE str1, VALUE str2)
{
unsigned int code;
rb_encoding *enc = STR_ENC_GET(str1);
int encidx;
if (RB_INTEGER_TYPE_P(str2)) {
if (rb_num_to_uint(str2, &code) == 0) {
}
else if (FIXNUM_P(str2)) {
rb_raise(rb_eRangeError, "%ld out of char range", FIX2LONG(str2));
}
else {
rb_raise(rb_eRangeError, "bignum out of char range");
}
}
else {
return rb_str_append(str1, str2);
}
encidx = rb_ascii8bit_appendable_encoding_index(enc, code);
if (encidx >= 0) {
rb_str_buf_cat_byte(str1, (unsigned char)code);
}
else {
rb_len_t pos = RSTRING_LEN(str1);
int cr = ENC_CODERANGE(str1);
int len;
char *buf;
switch (len = rb_enc_codelen(code, enc)) {
case ONIGERR_INVALID_CODE_POINT_VALUE:
rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
break;
case ONIGERR_TOO_BIG_WIDE_CHAR_VALUE:
case 0:
rb_raise(rb_eRangeError, "%u out of char range", code);
break;
}
buf = ALLOCA_N(char, len + 1);
rb_enc_mbcput(code, buf, enc);
if (rb_enc_precise_mbclen(buf, buf + len + 1, enc) != len) {
rb_raise(rb_eRangeError, "invalid codepoint 0x%X in %s", code, rb_enc_name(enc));
}
rb_str_resize(str1, pos+len);
memcpy(RSTRING_PTR(str1) + pos, buf, len);
if (cr == ENC_CODERANGE_7BIT && code > 127) {
cr = ENC_CODERANGE_VALID;
}
else if (cr == ENC_CODERANGE_BROKEN) {
cr = ENC_CODERANGE_UNKNOWN;
}
ENC_CODERANGE_SET(str1, cr);
}
return str1;
}
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.