instance method
String#b
() -> ::String
b → new_string
string.c
View on GitHub ↗
static VALUE
rb_str_b(VALUE str)
{
VALUE str2;
if (STR_EMBED_P(str)) {
str2 = str_alloc_embed(rb_cString, RSTRING_LEN(str) + TERM_LEN(str));
}
else {
str2 = str_alloc_heap(rb_cString);
}
str_replace_shared_without_enc(str2, str);
if (rb_enc_asciicompat(STR_ENC_GET(str))) {
// BINARY strings can never be broken; they're either 7-bit ASCII or VALID.
// If we know the receiver's code range then we know the result's code range.
int cr = ENC_CODERANGE(str);
switch (cr) {
case ENC_CODERANGE_7BIT:
ENC_CODERANGE_SET(str2, ENC_CODERANGE_7BIT);
break;
case ENC_CODERANGE_BROKEN:
case ENC_CODERANGE_VALID:
ENC_CODERANGE_SET(str2, ENC_CODERANGE_VALID);
break;
default:
ENC_CODERANGE_CLEAR(str2);
break;
}
}
return str2;
}
Returns a copy of self that has ASCII-8BIT encoding; the underlying bytes are not modified:
Example
s = "\x99" s.encoding # => #<Encoding:UTF-8> t = s.b # => "\x99" t.encoding # => #<Encoding:ASCII-8BIT> s = "\u4095" # => "䂕" s.encoding # => #<Encoding:UTF-8> s.bytes # => [228, 130, 149] t = s.b # => "\xE4\x82\x95" t.encoding # => #<Encoding:ASCII-8BIT> t.bytes # => [228, 130, 149]
Related: see Converting to New String.
See also
#ascii_only?
#byteindex
#append_as_bytes
#byterindex
also in
4.1 · 3.4 · 3.3 · 3.2 · 3.1 · 3.0