In Files

  • complex.c
  • pack.c
  • rational.c
  • string.c
  • transcode.c

String

A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals.

Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object. Typically, methods with names ending in “!'' modify their receiver, while those without a “!'' return a new String. However, there are exceptions, such as String#[]=.

Public Class Methods

new(str="") => new_str click to toggle source

Returns a new string object containing a copy of str.

 
               static VALUE
rb_str_init(int argc, VALUE *argv, VALUE str)
{
    VALUE orig;

    if (argc > 0 && rb_scan_args(argc, argv, "01", &orig) == 1)
        rb_str_replace(str, orig);
    return str;
}
            
try_convert(obj) → string or nil click to toggle source

Try to convert obj into a String, using #to_str method. Returns converted string or nil if obj cannot be converted for any reason.

String.try_convert("str")     # => str
String.try_convert(/re/)      # => nil
 
               static VALUE
rb_str_s_try_convert(VALUE dummy, VALUE str)
{
    return rb_check_string_type(str);
}
            

Public Instance Methods

str % arg => new_str click to toggle source

Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted. See Kernel::sprintf for details of the format string.

"%05d" % 123                              #=> "00123"
"%-5s: %08x" % [ "ID", self.object_id ]   #=> "ID   : 200e14d6"
 
               static VALUE
rb_str_format_m(VALUE str, VALUE arg)
{
    volatile VALUE tmp = rb_check_array_type(arg);

    if (!NIL_P(tmp)) {
        return rb_str_format(RARRAY_LEN(tmp), RARRAY_PTR(tmp), str);
    }
    return rb_str_format(1, &arg, str);
}
            
str * integer => new_str click to toggle source

Copy—Returns a new String containing integer copies of the receiver.

"Ho! " * 3   #=> "Ho! Ho! Ho! "
 
               VALUE
rb_str_times(VALUE str, VALUE times)
{
    VALUE str2;
    long n, len;

    len = NUM2LONG(times);
    if (len < 0) {
        rb_raise(rb_eArgError, "negative argument");
    }
    if (len && LONG_MAX/len <  RSTRING_LEN(str)) {
        rb_raise(rb_eArgError, "argument too big");
    }

    str2 = rb_str_new5(str, 0, len *= RSTRING_LEN(str));
    if (len) {
        n = RSTRING_LEN(str);
        memcpy(RSTRING_PTR(str2), RSTRING_PTR(str), n);
        while (n <= len/2) {
            memcpy(RSTRING_PTR(str2) + n, RSTRING_PTR(str2), n);
            n *= 2;
        }
        memcpy(RSTRING_PTR(str2) + n, RSTRING_PTR(str2), len-n);
    }
    RSTRING_PTR(str2)[RSTRING_LEN(str2)] = '\0';
    OBJ_INFECT(str2, str);
    rb_enc_cr_str_copy_for_substr(str2, str);

    return str2;
}
            
str + other_str => new_str click to toggle source

Concatenation—Returns a new String containing other_str concatenated to str.

"Hello from " + self.to_s   #=> "Hello from main"
 
               VALUE
rb_str_plus(VALUE str1, VALUE str2)
{
    VALUE str3;
    rb_encoding *enc;

    StringValue(str2);
    enc = rb_enc_check(str1, str2);
    str3 = rb_str_new(0, RSTRING_LEN(str1)+RSTRING_LEN(str2));
    memcpy(RSTRING_PTR(str3), RSTRING_PTR(str1), RSTRING_LEN(str1));
    memcpy(RSTRING_PTR(str3) + RSTRING_LEN(str1),
           RSTRING_PTR(str2), RSTRING_LEN(str2));
    RSTRING_PTR(str3)[RSTRING_LEN(str3)] = '\0';

    if (OBJ_TAINTED(str1) || OBJ_TAINTED(str2))
        OBJ_TAINT(str3);
    ENCODING_CODERANGE_SET(str3, rb_enc_to_index(enc),
                           ENC_CODERANGE_AND(ENC_CODERANGE(str1), ENC_CODERANGE(str2)));
    return str3;
}
            
str << integer => str click to toggle source
str << obj => str

Append—Concatenates the given object to str. If the object is a Integer, it is considered as a codepoint, and is converted to a character before concatenation.

a = "hello "
a << "world"   #=> "hello world"
a.concat(33)   #=> "hello world!"
 
               VALUE
rb_str_concat(VALUE str1, VALUE str2)
{
    if (FIXNUM_P(str2) || TYPE(str2) == T_BIGNUM) {
        rb_encoding *enc = STR_ENC_GET(str1);
        unsigned int c = NUM2UINT(str2);
        int pos = RSTRING_LEN(str1);
        int len = rb_enc_codelen(c, enc);
        int cr = ENC_CODERANGE(str1);

        rb_str_resize(str1, pos+len);
        rb_enc_mbcput(c, RSTRING_PTR(str1)+pos, enc);
        ENC_CODERANGE_SET(str1, cr);
        return str1;
    }
    return rb_str_append(str1, str2);
}
            
str <=> other_str => -1, 0, +1 click to toggle source

Comparison—Returns -1 if other_str is greater than, 0 if other_str is equal to, and +1 if other_str is less than str. If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one. In older versions of Ruby, setting $= allowed case-insensitive comparisons; this is now deprecated in favor of using String#casecmp.

<=> is the basis for the methods <, <=, >, >=, and between?, included from module Comparable. The method String#== does not use Comparable#==.

"abcdef" <=> "abcde"     #=> 1
"abcdef" <=> "abcdef"    #=> 0
"abcdef" <=> "abcdefg"   #=> -1
"abcdef" <=> "ABCDEF"    #=> 1
 
               static VALUE
rb_str_cmp_m(VALUE str1, VALUE str2)
{
    long result;

    if (TYPE(str2) != T_STRING) {
        if (!rb_respond_to(str2, rb_intern("to_str"))) {
            return Qnil;
        }
        else if (!rb_respond_to(str2, rb_intern("<=>"))) {
            return Qnil;
        }
        else {
            VALUE tmp = rb_funcall(str2, rb_intern("<=>"), 1, str1);

            if (NIL_P(tmp)) return Qnil;
            if (!FIXNUM_P(tmp)) {
                return rb_funcall(LONG2FIX(0), '-', 1, tmp);
            }
            result = -FIX2LONG(tmp);
        }
    }
    else {
        result = rb_str_cmp(str1, str2);
    }
    return LONG2NUM(result);
}
            
str == obj => true or false click to toggle source

Equality—If obj is not a String, returns false. Otherwise, returns true if str <=> obj returns zero.

 
               VALUE
rb_str_equal(VALUE str1, VALUE str2)
{
    int len;

    if (str1 == str2) return Qtrue;
    if (TYPE(str2) != T_STRING) {
        if (!rb_respond_to(str2, rb_intern("to_str"))) {
            return Qfalse;
        }
        return rb_equal(str2, str1);
    }
    if (!rb_str_comparable(str1, str2)) return Qfalse;
    if (RSTRING_LEN(str1) == (len = RSTRING_LEN(str2)) &&
        memcmp(RSTRING_PTR(str1), RSTRING_PTR(str2), len) == 0) {
        return Qtrue;
    }
    return Qfalse;
}
            
str == obj => true or false click to toggle source

Equality—If obj is not a String, returns false. Otherwise, returns true if str <=> obj returns zero.

 
               VALUE
rb_str_equal(VALUE str1, VALUE str2)
{
    int len;

    if (str1 == str2) return Qtrue;
    if (TYPE(str2) != T_STRING) {
        if (!rb_respond_to(str2, rb_intern("to_str"))) {
            return Qfalse;
        }
        return rb_equal(str2, str1);
    }
    if (!rb_str_comparable(str1, str2)) return Qfalse;
    if (RSTRING_LEN(str1) == (len = RSTRING_LEN(str2)) &&
        memcmp(RSTRING_PTR(str1), RSTRING_PTR(str2), len) == 0) {
        return Qtrue;
    }
    return Qfalse;
}
            
str =~ obj => fixnum or nil click to toggle source

Match—If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false.

"cat o' 9 tails" =~ /\d/   #=> 7
"cat o' 9 tails" =~ 9      #=> nil
 
               static VALUE
rb_str_match(VALUE x, VALUE y)
{
    switch (TYPE(y)) {
      case T_STRING:
        rb_raise(rb_eTypeError, "type mismatch: String given");

      case T_REGEXP:
        return rb_reg_match(y, x);

      default:
        return rb_funcall(y, rb_intern("=~"), 1, x);
    }
}
            
str[fixnum] => new_str or nil click to toggle source
str[fixnum, fixnum] => new_str or nil
str[range] => new_str or nil
str[regexp] => new_str or nil
str[regexp, fixnum] => new_str or nil
str[other_str] => new_str or nil

Element Reference—If passed a single Fixnum, returns a substring of one character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end.

If a Regexp is supplied, the matching portion of str is returned. If a numeric parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil
 
               static VALUE
rb_str_aref_m(int argc, VALUE *argv, VALUE str)
{
    if (argc == 2) {
        if (TYPE(argv[0]) == T_REGEXP) {
            return rb_str_subpat(str, argv[0], NUM2INT(argv[1]));
        }
        return rb_str_substr(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]));
    }
    if (argc != 1) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    return rb_str_aref(str, argv[0]);
}
            
str[fixnum] = new_str click to toggle source
str[fixnum, fixnum] = new_str
str[range] = aString
str[regexp] = new_str
str[regexp, fixnum] = new_str
str[other_str] = new_str

Element Assignment—Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as String#[]. If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. If the regular expression or string is used as the index doesn't match a position in the string, IndexError is raised. If the regular expression form is used, the optional second Fixnum allows you to specify which portion of the match to replace (effectively using the MatchData indexing rules. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment.

 
               static VALUE
rb_str_aset_m(int argc, VALUE *argv, VALUE str)
{
    if (argc == 3) {
        if (TYPE(argv[0]) == T_REGEXP) {
            rb_str_subpat_set(str, argv[0], NUM2INT(argv[1]), argv[2]);
        }
        else {
            rb_str_splice(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
        }
        return argv[2];
    }
    if (argc != 2) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc);
    }
    return rb_str_aset(str, argv[0], argv[1]);
}
            
ascii_only? => true or false click to toggle source

Returns true for a string which has only ASCII characters.

"abc".force_encoding("UTF-8").ascii_only? => true
"abc\u{6666}".force_encoding("UTF-8").ascii_only? => false
 
               static VALUE
rb_str_is_ascii_only_p(VALUE str)
{
    int cr = rb_enc_str_coderange(str);

    return cr == ENC_CODERANGE_7BIT ? Qtrue : Qfalse;
}
            
bytes => anEnumerator click to toggle source
bytes {|fixnum| block } => str

Returns an enumerator that gives each byte in the string. If a block is given, it iterates over each byte in the string.

"hello".bytes.to_a        #=> [104, 101, 108, 108, 111]
 
               static VALUE
rb_str_each_byte(VALUE str)
{
    long i;

    RETURN_ENUMERATOR(str, 0, 0);
    for (i=0; i<RSTRING_LEN(str); i++) {
        rb_yield(INT2FIX(RSTRING_PTR(str)[i] & 0xff));
    }
    return str;
}
            
bytesize => integer click to toggle source

Returns the length of str in bytes.

 
               static VALUE
rb_str_bytesize(VALUE str)
{
    return INT2NUM(RSTRING_LEN(str));
}
            
capitalize => new_str click to toggle source

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase. Note: case conversion is effective only in ASCII region.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"
 
               static VALUE
rb_str_capitalize(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_capitalize_bang(str);
    return str;
}
            
capitalize! => str or nil click to toggle source

Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made. Note: case conversion is effective only in ASCII region.

a = "hello"
a.capitalize!   #=> "Hello"
a               #=> "Hello"
a.capitalize!   #=> nil
 
               static VALUE
rb_str_capitalize_bang(VALUE str)
{
    rb_encoding *enc;
    char *s, *send;
    int modify = 0;
    unsigned int c;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    rb_str_check_dummy_enc(enc);
    if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil;
    s = RSTRING_PTR(str); send = RSTRING_END(str);

    c = rb_enc_codepoint(s, send, enc);
    if (rb_enc_islower(c, enc)) {
        rb_enc_mbcput(rb_enc_toupper(c, enc), s, enc);
        modify = 1;
    }
    s += rb_enc_codelen(c, enc);
    while (s < send) {
        c = rb_enc_codepoint(s, send, enc);
        if (rb_enc_isupper(c, enc)) {
            rb_enc_mbcput(rb_enc_tolower(c, enc), s, enc);
            modify = 1;
        }
        s += rb_enc_codelen(c, enc);
    }

    if (modify) return str;
    return Qnil;
}
            
casecmp(other_str) => -1, 0, +1 click to toggle source

Case-insensitive version of String#<=>.

"abcdef".casecmp("abcde")     #=> 1
"aBcDeF".casecmp("abcdef")    #=> 0
"abcdef".casecmp("abcdefg")   #=> -1
"abcdef".casecmp("ABCDEF")    #=> 0
 
               static VALUE
rb_str_casecmp(VALUE str1, VALUE str2)
{
    long len;
    rb_encoding *enc;
    char *p1, *p1end, *p2, *p2end;

    StringValue(str2);
    enc = rb_enc_compatible(str1, str2);
    if (!enc) {
        return Qnil;
    }

    p1 = RSTRING_PTR(str1); p1end = RSTRING_END(str1);
    p2 = RSTRING_PTR(str2); p2end = RSTRING_END(str2);
    if (single_byte_optimizable(str1) && single_byte_optimizable(str2)) {
        while (p1 < p1end && p2 < p2end) {
            if (*p1 != *p2) {
                unsigned int c1 = TOUPPER(*p1 & 0xff);
                unsigned int c2 = TOUPPER(*p2 & 0xff);
                if (c1 != c2)
                    return INT2FIX(c1 < c2 ? -1 : 1);
            }
            p1++;
            p2++;
        }
    }
    else {
        while (p1 < p1end && p2 < p2end) {
            int l1, c1 = rb_enc_ascget(p1, p1end, &l1, enc);
            int l2, c2 = rb_enc_ascget(p2, p2end, &l2, enc);

            if (0 <= c1 && 0 <= c2) {
                c1 = TOUPPER(c1);
                c2 = TOUPPER(c2);
                if (c1 != c2)
                    return INT2FIX(c1 < c2 ? -1 : 1);
            }
            else {
                int r;
                l1 = rb_enc_mbclen(p1, p1end, enc);
                l2 = rb_enc_mbclen(p2, p2end, enc);
                len = l1 < l2 ? l1 : l2;
                r = memcmp(p1, p2, len);
                if (r != 0)
                    return INT2FIX(r < 0 ? -1 : 1);
                if (l1 != l2)
                    return INT2FIX(l1 < l2 ? -1 : 1);
            }
            p1 += l1;
            p2 += l2;
        }
    }
    if (RSTRING_LEN(str1) == RSTRING_LEN(str2)) return INT2FIX(0);
    if (RSTRING_LEN(str1) > RSTRING_LEN(str2)) return INT2FIX(1);
    return INT2FIX(-1);
}
            
center(integer, padstr) => new_str click to toggle source

If integer is greater than the length of str, returns a new String of length integer with str centered and padded with padstr; otherwise, returns str.

"hello".center(4)         #=> "hello"
"hello".center(20)        #=> "       hello        "
"hello".center(20, '123') #=> "1231231hello12312312"
 
               static VALUE
rb_str_center(int argc, VALUE *argv, VALUE str)
{
    return rb_str_justify(argc, argv, str, 'c');
}
            
chars => anEnumerator click to toggle source
chars {|substr| block } => str

Returns an enumerator that gives each character in the string. If a block is given, it iterates over each character in the string.

"foo".chars.to_a   #=> ["f","o","o"]
 
               static VALUE
rb_str_each_char(VALUE str)
{
    long i, len, n;
    const char *ptr;
    rb_encoding *enc;

    RETURN_ENUMERATOR(str, 0, 0);
    str = rb_str_new4(str);
    ptr = RSTRING_PTR(str);
    len = RSTRING_LEN(str);
    enc = rb_enc_get(str);
    for (i = 0; i < len; i += n) {
        n = rb_enc_mbclen(ptr + i, ptr + len, enc);
        rb_yield(rb_str_subseq(str, i, n));
    }
    return str;
}
            
chomp(separator=$/) => new_str click to toggle source

Returns a new String with the given record separator removed from the end of str (if present). If $/ has not been changed from the default Ruby record separator, then chomp also removes carriage return characters (that is it will remove \n, \r, and \r\n).

"hello".chomp            #=> "hello"
"hello\n".chomp          #=> "hello"
"hello\r\n".chomp        #=> "hello"
"hello\n\r".chomp        #=> "hello\n"
"hello\r".chomp          #=> "hello"
"hello \n there".chomp   #=> "hello \n there"
"hello".chomp("llo")     #=> "he"
 
               static VALUE
rb_str_chomp(int argc, VALUE *argv, VALUE str)
{
    str = rb_str_dup(str);
    rb_str_chomp_bang(argc, argv, str);
    return str;
}
            
chomp!(separator=$/) => str or nil click to toggle source

Modifies str in place as described for String#chomp, returning str, or nil if no modifications were made.

 
               static VALUE
rb_str_chomp_bang(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    VALUE rs;
    int newline;
    char *p, *pp, *e;
    long len, rslen;

    len = RSTRING_LEN(str);
    if (len == 0) return Qnil;
    p = RSTRING_PTR(str);
    e = p + len;
    if (argc == 0) {
        rs = rb_rs;
        if (rs == rb_default_rs) {
          smart_chomp:
            str_modify_keep_cr(str);
            enc = rb_enc_get(str);
            if (rb_enc_mbminlen(enc) > 1) {
                pp = rb_enc_left_char_head(p, e-rb_enc_mbminlen(enc), e, enc);
                if (rb_enc_is_newline(pp, e, enc)) {
                    e = pp;
                }
                pp = e - rb_enc_mbminlen(enc);
                if (pp >= p) {
                    pp = rb_enc_left_char_head(p, pp, e, enc);
                    if (rb_enc_ascget(pp, e, 0, enc) == '\r') {
                        e = pp;
                    }
                }
                if (e == RSTRING_END(str)) {
                    return Qnil;
                }
                len = e - RSTRING_PTR(str);
                STR_SET_LEN(str, len);
            }
            else {
                if (RSTRING_PTR(str)[len-1] == '\n') {
                    STR_DEC_LEN(str);
                    if (RSTRING_LEN(str) > 0 &&
                        RSTRING_PTR(str)[RSTRING_LEN(str)-1] == '\r') {
                        STR_DEC_LEN(str);
                    }
                }
                else if (RSTRING_PTR(str)[len-1] == '\r') {
                    STR_DEC_LEN(str);
                }
                else {
                    return Qnil;
                }
            }
            RSTRING_PTR(str)[RSTRING_LEN(str)] = '\0';
            return str;
        }
    }
    else {
        rb_scan_args(argc, argv, "01", &rs);
    }
    if (NIL_P(rs)) return Qnil;
    StringValue(rs);
    rslen = RSTRING_LEN(rs);
    if (rslen == 0) {
        while (len>0 && p[len-1] == '\n') {
            len--;
            if (len>0 && p[len-1] == '\r')
                len--;
        }
        if (len < RSTRING_LEN(str)) {
            str_modify_keep_cr(str);
            STR_SET_LEN(str, len);
            RSTRING_PTR(str)[len] = '\0';
            return str;
        }
        return Qnil;
    }
    if (rslen > len) return Qnil;
    newline = RSTRING_PTR(rs)[rslen-1];
    if (rslen == 1 && newline == '\n')
        goto smart_chomp;

    enc = rb_enc_check(str, rs);
    if (is_broken_string(rs)) {
        return Qnil;
    }
    pp = e - rslen;
    if (p[len-1] == newline &&
        (rslen <= 1 ||
         memcmp(RSTRING_PTR(rs), pp, rslen) == 0)) {
        if (rb_enc_left_char_head(p, pp, e, enc) != pp)
            return Qnil;
        rb_str_modify(str);
        STR_SET_LEN(str, RSTRING_LEN(str) - rslen);
        RSTRING_PTR(str)[RSTRING_LEN(str)] = '\0';
        return str;
    }
    return Qnil;
}
            
chop => new_str click to toggle source

Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn't end in a record separator.

"string\r\n".chop   #=> "string"
"string\n\r".chop   #=> "string\n"
"string\n".chop     #=> "string"
"string".chop       #=> "strin"
"x".chop.chop       #=> ""
 
               static VALUE
rb_str_chop(VALUE str)
{
    VALUE str2 = rb_str_new5(str, RSTRING_PTR(str), chopped_length(str));
    rb_enc_cr_str_copy_for_substr(str2, str);
    OBJ_INFECT(str2, str);
    return str2;
}
            
chop! => str or nil click to toggle source

Processes str as for String#chop, returning str, or nil if str is the empty string. See also String#chomp!.

 
               static VALUE
rb_str_chop_bang(VALUE str)
{
    if (RSTRING_LEN(str) > 0) {
        long len;
        rb_str_modify(str);
        len = chopped_length(str);
        STR_SET_LEN(str, len);
        RSTRING_PTR(str)[len] = '\0';
        return str;
    }
    return Qnil;
}
            
chr → string click to toggle source

Returns a one-character string at the beginning of the string.

a = "abcde"
a.chr    #=> "a"
 
               static VALUE
rb_str_chr(VALUE str)
{
    return rb_str_substr(str, 0, 1);
}
            
clear → string click to toggle source

Makes string empty.

a = "abcde"
a.clear    #=> ""
 
               static VALUE
rb_str_clear(VALUE str)
{
    /* rb_str_modify() */       /* no need for str_make_independent */
    if (str_independent(str) && !STR_EMBED_P(str)) {
        xfree(RSTRING_PTR(str));
    }
    STR_SET_EMBED(str);
    STR_SET_EMBED_LEN(str, 0);
    RSTRING_PTR(str)[0] = 0;
    if (rb_enc_asciicompat(STR_ENC_GET(str)))
        ENC_CODERANGE_SET(str, ENC_CODERANGE_7BIT);
    else
        ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID);
    return str;
}
            
codepoints => anEnumerator click to toggle source
codepoints {|fixnum| block } => str

Returns an enumerator that gives the Integer ordinal of each character in the string, also known as a codepoint when applied to Unicode strings. If a block is given, it iterates over each character in the string.

"foo\u0635".codepoints.to_a   #=> [102, 111, 111, 1589]
 
               static VALUE
rb_str_each_codepoint(VALUE str)
{
    long len;
    int n;
    unsigned int c;
    const char *ptr, *end;
    rb_encoding *enc;

    if (single_byte_optimizable(str)) return rb_str_each_byte(str);
    RETURN_ENUMERATOR(str, 0, 0);
    ptr = RSTRING_PTR(str);
    len = RSTRING_LEN(str);
    end = RSTRING_END(str);
    enc = STR_ENC_GET(str);
    while (ptr < end) {
        c = rb_enc_codepoint(ptr, end, enc);
        n = rb_enc_codelen(c, enc);
        rb_yield(UINT2NUM(c));
        ptr += n;
    }
    return str;
}
            
concat(integer) => str click to toggle source
concat(obj) => str

Append—Concatenates the given object to str. If the object is a Integer, it is considered as a codepoint, and is converted to a character before concatenation.

a = "hello "
a << "world"   #=> "hello world"
a.concat(33)   #=> "hello world!"
 
               VALUE
rb_str_concat(VALUE str1, VALUE str2)
{
    if (FIXNUM_P(str2) || TYPE(str2) == T_BIGNUM) {
        rb_encoding *enc = STR_ENC_GET(str1);
        unsigned int c = NUM2UINT(str2);
        int pos = RSTRING_LEN(str1);
        int len = rb_enc_codelen(c, enc);
        int cr = ENC_CODERANGE(str1);

        rb_str_resize(str1, pos+len);
        rb_enc_mbcput(c, RSTRING_PTR(str1)+pos, enc);
        ENC_CODERANGE_SET(str1, cr);
        return str1;
    }
    return rb_str_append(str1, str2);
}
            
count([other_str]+) => fixnum click to toggle source

Each other_str parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any other_str that starts with a caret (^) is negated. The sequence c1–c2 means all characters between c1 and c2.

a = "hello world"
a.count "lo"            #=> 5
a.count "lo", "o"       #=> 2
a.count "hello", "^l"   #=> 4
a.count "ej-m"          #=> 4
 
               static VALUE
rb_str_count(int argc, VALUE *argv, VALUE str)
{
    char table[256];
    rb_encoding *enc = 0;
    VALUE del = 0, nodel = 0;
    char *s, *send;
    int i;
    int ascompat;

    if (argc < 1) {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    for (i=0; i<argc; i++) {
        VALUE s = argv[i];

        StringValue(s);
        enc = rb_enc_check(str, s);
        tr_setup_table(s, table, i==0, &del, &nodel, enc);
    }

    s = RSTRING_PTR(str);
    if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0);
    send = RSTRING_END(str);
    i = 0;
    ascompat = rb_enc_asciicompat(enc);

    while (s < send) {
        unsigned int c;
        int clen;

        if (ascompat && (c = *(unsigned char*)s) < 0x80) {
            clen = 1;
            if (table[c]) {
                i++;
            }
            s++;
        }
        else {
            c = rb_enc_codepoint(s, send, enc);
            clen = rb_enc_codelen(c, enc);
            if (tr_find(c, table, del, nodel)) {
                i++;
            }
            s += clen;
        }
    }

    return INT2NUM(i);
}
            
crypt(other_str) => new_str click to toggle source

Applies a one-way cryptographic hash to str by invoking the standard library function crypt. The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./].

 
               static VALUE
rb_str_crypt(VALUE str, VALUE salt)
{
    extern char *crypt(const char *, const char *);
    VALUE result;
    const char *s, *saltp;
#ifdef BROKEN_CRYPT
    char salt_8bit_clean[3];
#endif

    StringValue(salt);
    if (RSTRING_LEN(salt) < 2)
        rb_raise(rb_eArgError, "salt too short (need >=2 bytes)");

    s = RSTRING_PTR(str);
    if (!s) s = "";
    saltp = RSTRING_PTR(salt);
#ifdef BROKEN_CRYPT
    if (!ISASCII((unsigned char)saltp[0]) || !ISASCII((unsigned char)saltp[1])) {
        salt_8bit_clean[0] = saltp[0] & 0x7f;
        salt_8bit_clean[1] = saltp[1] & 0x7f;
        salt_8bit_clean[2] = '\0';
        saltp = salt_8bit_clean;
    }
#endif
    result = rb_str_new2(crypt(s, saltp));
    OBJ_INFECT(result, str);
    OBJ_INFECT(result, salt);
    return result;
}
            
delete([other_str]+) => new_str click to toggle source

Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count.

"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"
 
               static VALUE
rb_str_delete(int argc, VALUE *argv, VALUE str)
{
    str = rb_str_dup(str);
    rb_str_delete_bang(argc, argv, str);
    return str;
}
            
delete!([other_str]+) => str or nil click to toggle source

Performs a delete operation in place, returning str, or nil if str was not modified.

 
               static VALUE
rb_str_delete_bang(int argc, VALUE *argv, VALUE str)
{
    char squeez[256];
    rb_encoding *enc = 0;
    char *s, *send, *t;
    VALUE del = 0, nodel = 0;
    int modify = 0;
    int i, ascompat, cr;

    if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil;
    if (argc < 1) {
        rb_raise(rb_eArgError, "wrong number of arguments");
    }
    for (i=0; i<argc; i++) {
        VALUE s = argv[i];

        StringValue(s);
        enc = rb_enc_check(str, s);
        tr_setup_table(s, squeez, i==0, &del, &nodel, enc);
    }

    str_modify_keep_cr(str);
    ascompat = rb_enc_asciicompat(enc);
    s = t = RSTRING_PTR(str);
    send = RSTRING_END(str);
    cr = ascompat ? ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID;
    while (s < send) {
        unsigned int c;
        int clen;

        if (ascompat && (c = *(unsigned char*)s) < 0x80) {
            if (squeez[c]) {
                modify = 1;
            }
            else {
                if (t != s) *t = c;
                t++;
            }
            s++;
        }
        else {
            c = rb_enc_codepoint(s, send, enc);
            clen = rb_enc_codelen(c, enc);

            if (tr_find(c, squeez, del, nodel)) {
                modify = 1;
            }
            else {
                if (t != s) rb_enc_mbcput(c, t, enc);
                t += clen;
                if (cr == ENC_CODERANGE_7BIT) cr = ENC_CODERANGE_VALID;
            }
            s += clen;
        }
    }
    *t = '\0';
    STR_SET_LEN(str, t - RSTRING_PTR(str));
    ENC_CODERANGE_SET(str, cr);

    if (modify) return str;
    return Qnil;
}
            
downcase => new_str click to toggle source

Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale insensitive—only characters “A'' to “Z'' are affected. Note: case replacement is effective only in ASCII region.

"hEllO".downcase   #=> "hello"
 
               static VALUE
rb_str_downcase(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_downcase_bang(str);
    return str;
}
            
downcase! => str or nil click to toggle source

Downcases the contents of str, returning nil if no changes were made. Note: case replacement is effective only in ASCII region.

 
               static VALUE
rb_str_downcase_bang(VALUE str)
{
    rb_encoding *enc;
    char *s, *send;
    int modify = 0;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    rb_str_check_dummy_enc(enc);
    s = RSTRING_PTR(str); send = RSTRING_END(str);
    if (single_byte_optimizable(str)) {
        while (s < send) {
            unsigned int c = *(unsigned char*)s;

            if (rb_enc_isascii(c, enc) && 'A' <= c && c <= 'Z') {
                *s = 'a' + (c - 'A');
                modify = 1;
            }
            s++;
        }
    }
    else {
        int ascompat = rb_enc_asciicompat(enc);

        while (s < send) {
            unsigned int c;

            if (ascompat && (c = *(unsigned char*)s) < 0x80) {
                if (rb_enc_isascii(c, enc) && 'A' <= c && c <= 'Z') {
                    *s = 'a' + (c - 'A');
                    modify = 1;
                }
                s++;
            }
            else {
                c = rb_enc_codepoint(s, send, enc);
                if (rb_enc_isupper(c, enc)) {
                    /* assuming toupper returns codepoint with same size */
                    rb_enc_mbcput(rb_enc_tolower(c, enc), s, enc);
                    modify = 1;
                }
                s += rb_enc_codelen(c, enc);
            }
        }
    }

    if (modify) return str;
    return Qnil;
}
            
dump => new_str click to toggle source

Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped.

 
               VALUE
rb_str_dump(VALUE str)
{
    rb_encoding *enc = rb_enc_get(str);
    long len;
    const char *p, *pend;
    char *q, *qend;
    VALUE result;
    int u8 = (enc == rb_utf8_encoding());

    len = 2;                    /* "" */
    p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
    while (p < pend) {
        unsigned char c = *p++;
        switch (c) {
          case '"':  case '\\':
          case '\n': case '\r':
          case '\t': case '\f':
          case '\013': case '\010': case '\007': case '\033':
            len += 2;
            break;

          case '#':
            len += IS_EVSTR(p, pend) ? 2 : 1;
            break;

          default:
            if (ISPRINT(c)) {
                len++;
            }
            else {
                if (u8) {     /* \u{NN} */
                    char buf[32];
                    int n = rb_enc_precise_mbclen(p-1, pend, enc) - 1;
                    if (MBCLEN_CHARFOUND_P(n)) {
                        int cc = rb_enc_codepoint(p-1, pend, enc);
                        sprintf(buf, "%x", cc);
                        len += strlen(buf)+4;
                        p += n;
                        break;
                    }
                }
                len += 4;     /* \xNN */
            }
            break;
        }
    }
    if (!rb_enc_asciicompat(enc)) {
        len += 19;             /* ".force_encoding('')" */
        len += strlen(enc->name);
    }

    result = rb_str_new5(str, 0, len);
    p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
    q = RSTRING_PTR(result); qend = q + len + 1;

    *q++ = '"';
    while (p < pend) {
        unsigned char c = *p++;

        if (c == '"' || c == '\\') {
            *q++ = '\\';
            *q++ = c;
        }
        else if (c == '#') {
            if (IS_EVSTR(p, pend)) *q++ = '\\';
            *q++ = '#';
        }
        else if (c == '\n') {
            *q++ = '\\';
            *q++ = 'n';
        }
        else if (c == '\r') {
            *q++ = '\\';
            *q++ = 'r';
        }
        else if (c == '\t') {
            *q++ = '\\';
            *q++ = 't';
        }
        else if (c == '\f') {
            *q++ = '\\';
            *q++ = 'f';
        }
        else if (c == '\013') {
            *q++ = '\\';
            *q++ = 'v';
        }
        else if (c == '\010') {
            *q++ = '\\';
            *q++ = 'b';
        }
        else if (c == '\007') {
            *q++ = '\\';
            *q++ = 'a';
        }
        else if (c == '\033') {
            *q++ = '\\';
            *q++ = 'e';
        }
        else if (ISPRINT(c)) {
            *q++ = c;
        }
        else {
            *q++ = '\\';
            if (u8) {
                int n = rb_enc_precise_mbclen(p-1, pend, enc) - 1;
                if (MBCLEN_CHARFOUND_P(n)) {
                    int cc = rb_enc_codepoint(p-1, pend, enc);
                    p += n;
                    sprintf(q, "u{%x}", cc);
                    q += strlen(q);
                    continue;
                }
            }
            sprintf(q, "x%02X", c);
            q += 3;
        }
    }
    *q++ = '"';
    *q = '\0';
    if (!rb_enc_asciicompat(enc)) {
        sprintf(q, ".force_encoding(\"%s\")", enc->name);
        enc = rb_ascii8bit_encoding();
    }
    OBJ_INFECT(result, str);
    /* result from dump is ASCII */
    rb_enc_associate(result, enc);
    ENC_CODERANGE_SET(result, ENC_CODERANGE_7BIT);
    return result;
}
            
each_byte {|fixnum| block } => str click to toggle source

Passes each byte in str to the given block.

"hello".each_byte {|c| print c, ' ' }

produces:

104 101 108 108 111
 
               static VALUE
rb_str_each_byte(VALUE str)
{
    long i;

    RETURN_ENUMERATOR(str, 0, 0);
    for (i=0; i<RSTRING_LEN(str); i++) {
        rb_yield(INT2FIX(RSTRING_PTR(str)[i] & 0xff));
    }
    return str;
}
            
each_char {|cstr| block } => str click to toggle source

Passes each character in str to the given block.

"hello".each_char {|c| print c, ' ' }

produces:

h e l l o
 
               static VALUE
rb_str_each_char(VALUE str)
{
    long i, len, n;
    const char *ptr;
    rb_encoding *enc;

    RETURN_ENUMERATOR(str, 0, 0);
    str = rb_str_new4(str);
    ptr = RSTRING_PTR(str);
    len = RSTRING_LEN(str);
    enc = rb_enc_get(str);
    for (i = 0; i < len; i += n) {
        n = rb_enc_mbclen(ptr + i, ptr + len, enc);
        rb_yield(rb_str_subseq(str, i, n));
    }
    return str;
}
            
each_codepoint {|integer| block } => str click to toggle source

Passes the Integer ordinal of each character in str, also known as a codepoint when applied to Unicode strings to the given block.

"hello\u0639".each_codepoint {|c| print c, ' ' }

produces:

104 101 108 108 111 1593
 
               static VALUE
rb_str_each_codepoint(VALUE str)
{
    long len;
    int n;
    unsigned int c;
    const char *ptr, *end;
    rb_encoding *enc;

    if (single_byte_optimizable(str)) return rb_str_each_byte(str);
    RETURN_ENUMERATOR(str, 0, 0);
    ptr = RSTRING_PTR(str);
    len = RSTRING_LEN(str);
    end = RSTRING_END(str);
    enc = STR_ENC_GET(str);
    while (ptr < end) {
        c = rb_enc_codepoint(ptr, end, enc);
        n = rb_enc_codelen(c, enc);
        rb_yield(UINT2NUM(c));
        ptr += n;
    }
    return str;
}
            
each_line(separator=$/) {|substr| block } => str click to toggle source

Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split into paragraphs delimited by multiple successive newlines.

print "Example one\n"
"hello\nworld".each {|s| p s}
print "Example two\n"
"hello\nworld".each('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each('') {|s| p s}

produces:

Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"
 
               static VALUE
rb_str_each_line(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    VALUE rs;
    unsigned int newline;
    char *p, *pend, *s, *ptr;
    long len, rslen; 
    VALUE line;
    int n;
    VALUE orig = str;

    if (argc == 0) {
        rs = rb_rs;
    }
    else {
        rb_scan_args(argc, argv, "01", &rs);
    }
    RETURN_ENUMERATOR(str, argc, argv);
    if (NIL_P(rs)) {
        rb_yield(str);
        return orig;
    }
    str = rb_str_new4(str);
    ptr = p = s = RSTRING_PTR(str);
    pend = p + RSTRING_LEN(str);
    len = RSTRING_LEN(str);
    StringValue(rs);
    if (rs == rb_default_rs) {
        enc = rb_enc_get(str);
        while (p < pend) {
            char *p0;

            p = memchr(p, '\n', pend - p);
            if (!p) break;
            p0 = rb_enc_left_char_head(s, p, pend, enc);
            if (!rb_enc_is_newline(p0, pend, enc)) {
                p++;
                continue;
            }
            p = p0 + rb_enc_mbclen(p0, pend, enc);
            line = rb_str_new5(str, s, p - s);
            OBJ_INFECT(line, str);
            rb_enc_cr_str_copy_for_substr(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p;
        }
        goto finish;
    }

    enc = rb_enc_check(str, rs);
    rslen = RSTRING_LEN(rs);
    if (rslen == 0) {
        newline = '\n';
    }
    else {
        newline = rb_enc_codepoint(RSTRING_PTR(rs), RSTRING_END(rs), enc);
    }

    while (p < pend) {
        unsigned int c = rb_enc_codepoint(p, pend, enc);

      again:
        n = rb_enc_codelen(c, enc);
        if (rslen == 0 && c == newline) {
            p += n;
            if (p < pend && (c = rb_enc_codepoint(p, pend, enc)) != newline) {
                goto again;
            }
            while (p < pend && rb_enc_codepoint(p, pend, enc) == newline) {
                p += n;
            }
            p -= n;
        }
        if (c == newline &&
            (rslen <= 1 || memcmp(RSTRING_PTR(rs), p, rslen) == 0)) {
            line = rb_str_new5(str, s, p - s + (rslen ? rslen : n));
            OBJ_INFECT(line, str);
            rb_enc_cr_str_copy_for_substr(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p + (rslen ? rslen : n);
        }
        p += n;
    }

  finish:
    if (s != pend) {
        line = rb_str_new5(str, s, pend - s);
        OBJ_INFECT(line, str);
        rb_enc_cr_str_copy_for_substr(line, str);
        rb_yield(line);
    }

    return orig;
}
            
empty? => true or false click to toggle source

Returns true if str has a length of zero.

"hello".empty?   #=> false
"".empty?        #=> true
 
               static VALUE
rb_str_empty(VALUE str)
{
    if (RSTRING_LEN(str) == 0)
        return Qtrue;
    return Qfalse;
}
            
encode(encoding [, options] ) => str click to toggle source
encode(dst_encoding, src_encoding [, options] ) => str
encode([options]) => str

The first form returns a copy of str transcoded to encoding encoding. The second form returns a copy of str transcoded from src_encoding to dst_encoding. The last form returns a copy of str transcoded to Encoding.default_internal. By default, the first and second form raise Encoding::UndefinedConversionError for characters that are undefined in the destination encoding, and Encoding::InvalidByteSequenceError for invalid byte sequences in the source encoding. The last form by default does not raise exceptions but uses replacement strings. The options Hash gives details for conversion.

options

The hash options can have the following keys:

:invalid

If the value is :replace, #encode replaces invalid byte sequences in str with the replacement character. The default is to raise the exception

:undef

If the value is :replace, #encode replaces characters which are undefined in the destination encoding with the replacement character.

:replace

Sets the replacement string to the value. The default replacement string is “uFFFD” for Unicode encoding forms, and “?” otherwise.

:xml

The value must be :text or :attr. If the value is :text #encode replaces undefined characters with their (upper-case hexadecimal) numeric character references. '&', '<', and '>' are converted to “&amp;”, “&lt;”, and “&gt;”, respectively. If the value is :attr, #encode also quotes the replacement result (using '“'), and replaces '”' with “&quot;”.

:cr_newline

Replaces LF (“n”) with CR (“r”) if value is true.

:crlf_newline

Replaces LF (“n”) with CRLF (“rn”) if value is true.

:universal_newline

Replaces CRLF (“rn”) and CR (“r”) with LF (“n”) if value is true.

 
               static VALUE
str_encode(int argc, VALUE *argv, VALUE str)
{
    VALUE newstr = str;
    int encidx = str_transcode(argc, argv, &newstr);

    if (encidx < 0) return rb_str_dup(str);
    if (newstr == str) {
        newstr = rb_str_dup(str);
    }
    else {
        RBASIC(newstr)->klass = rb_obj_class(str);
    }
    return str_encode_associate(newstr, encidx);
}
            
encode!(encoding [, options] ) => str click to toggle source
encode!(dst_encoding, src_encoding [, options] ) => str

The first form transcodes the contents of str from str.encoding to encoding. The second form transcodes the contents of str from src_encoding to dst_encoding. The options Hash gives details for conversion. See #encode for details. Returns the string even if no changes were made.

 
               static VALUE
str_encode_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE newstr = str;
    int encidx = str_transcode(argc, argv, &newstr);

    if (encidx < 0) return str;
    rb_str_shared_replace(str, newstr);
    return str_encode_associate(str, encidx);
}
            
encoding => encoding click to toggle source

Returns the Encoding object that represents the encoding of obj.

 
               VALUE
rb_obj_encoding(VALUE obj)
{
    rb_encoding *enc = rb_enc_get(obj);
    if (!enc) {
	rb_raise(rb_eTypeError, "unknown encoding");
    }
    return rb_enc_from_encoding(enc);
}
            
end_with?([suffix]+) => true or false click to toggle source

Returns true if str ends with the suffix given.

 
               static VALUE
rb_str_end_with(int argc, VALUE *argv, VALUE str)
{
    int i;
    char *p, *s, *e;
    rb_encoding *enc;

    for (i=0; i<argc; i++) {
        VALUE tmp = rb_check_string_type(argv[i]);
        if (NIL_P(tmp)) continue;
        enc = rb_enc_check(str, tmp);
        if (RSTRING_LEN(str) < RSTRING_LEN(tmp)) continue;
        p = RSTRING_PTR(str);
        e = p + RSTRING_LEN(str);
        s = e - RSTRING_LEN(tmp);
        if (rb_enc_left_char_head(p, s, e, enc) != s)
            continue;
        if (memcmp(s, RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0)
            return Qtrue;
    }
    return Qfalse;
}
            
eql?(other) => true or false click to toggle source

Two strings are equal if the have the same length and content.

 
               static VALUE
rb_str_eql(VALUE str1, VALUE str2)
{
    if (TYPE(str2) != T_STRING || RSTRING_LEN(str1) != RSTRING_LEN(str2))
        return Qfalse;

    if (!rb_str_comparable(str1, str2)) return Qfalse;
    if (memcmp(RSTRING_PTR(str1), RSTRING_PTR(str2),
               lesser(RSTRING_LEN(str1), RSTRING_LEN(str2))) == 0)
        return Qtrue;

    return Qfalse;
}
            
force_encoding(encoding) => str click to toggle source

Changes the encoding to encoding and returns self.

 
               static VALUE
rb_str_force_encoding(VALUE str, VALUE enc)
{
    str_modifiable(str);
    rb_enc_associate(str, rb_to_encoding(enc));
    ENC_CODERANGE_CLEAR(str);
    return str;
}
            
getbyte(index) => 0 .. 255 click to toggle source

returns the indexth byte as an integer.

 
               static VALUE
rb_str_getbyte(VALUE str, VALUE index)
{
    long pos = NUM2LONG(index);

    if (pos < 0)
        pos += RSTRING_LEN(str);
    if (pos < 0 ||  RSTRING_LEN(str) <= pos)
        return Qnil;

    return INT2FIX((unsigned char)RSTRING_PTR(str)[pos]);
}
            
gsub(pattern, replacement) => new_str click to toggle source
gsub(pattern) {|match| block } => new_str

Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but '\d' will match a backslash followed by a 'd').

If a string is used as the replacement, special variables from the match (such as $& and $1) cannot be substituted into it, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, \k<group_name>, and so on may be used to interpolate successive groups in the match.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

"hello".gsub(/[aeiou]/, '*')                  #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>')             #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s[0].ord.to_s + ' '}   #=> "104 101 108 108 111 "
"hello".gsub(/(?<foo>[aeiou])/, '{\k<foo>}')  #=> "h{e}ll{o}"
 
               static VALUE
rb_str_gsub(int argc, VALUE *argv, VALUE str)
{
    return str_gsub(argc, argv, str, 0);
}
            
gsub!(pattern, replacement) => str or nil click to toggle source
gsub!(pattern) {|match| block } => str or nil

Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed.

 
               static VALUE
rb_str_gsub_bang(int argc, VALUE *argv, VALUE str)
{
    return str_gsub(argc, argv, str, 1);
}
            
hash => fixnum click to toggle source

Return a hash based on the string's length and content.

 
               static VALUE
rb_str_hash_m(VALUE str)
{
    int hval = rb_str_hash(str);
    return INT2FIX(hval);
}
            
hex => integer click to toggle source

Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional 0x) and returns the corresponding number. Zero is returned on error.

"0x0a".hex     #=> 10
"-1234".hex    #=> -4660
"0".hex        #=> 0
"wombat".hex   #=> 0
 
               static VALUE
rb_str_hex(VALUE str)
{
    rb_encoding *enc = rb_enc_get(str);

    if (!rb_enc_asciicompat(enc)) {
        rb_raise(rb_eEncCompatError, "ASCII incompatible encoding: %s", rb_enc_name(enc));
    }
    return rb_str_to_inum(str, 16, Qfalse);
}
            
include? other_str => true or false click to toggle source

Returns true if str contains the given string or character.

"hello".include? "lo"   #=> true
"hello".include? "ol"   #=> false
"hello".include? ?h     #=> true
 
               static VALUE
rb_str_include(VALUE str, VALUE arg)
{
    long i;

    StringValue(arg);
    i = rb_str_index(str, arg, 0);

    if (i == -1) return Qfalse;
    return Qtrue;
}
            
index(substring [, offset]) => fixnum or nil click to toggle source
index(regexp [, offset]) => fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4
 
               static VALUE
rb_str_index_m(int argc, VALUE *argv, VALUE str)
{
    VALUE sub;
    VALUE initpos;
    long pos;

    if (rb_scan_args(argc, argv, "11", &sub, &initpos) == 2) {
        pos = NUM2LONG(initpos);
    }
    else {
        pos = 0;
    }
    if (pos < 0) {
        pos += str_strlen(str, STR_ENC_GET(str));
        if (pos < 0) {
            if (TYPE(sub) == T_REGEXP) {
                rb_backref_set(Qnil);
            }
            return Qnil;
        }
    }

    switch (TYPE(sub)) {
      case T_REGEXP:
        if (pos > str_strlen(str, STR_ENC_GET(str)))
            return Qnil;
        pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos,
                         rb_enc_check(str, sub), single_byte_optimizable(str));

        pos = rb_reg_search(sub, str, pos, 0);
        pos = rb_str_sublen(str, pos);
        break;

      default: {
        VALUE tmp;

        tmp = rb_check_string_type(sub);
        if (NIL_P(tmp)) {
            rb_raise(rb_eTypeError, "type mismatch: %s given",
                     rb_obj_classname(sub));
        }
        sub = tmp;
      }
        /* fall through */
      case T_STRING:
        pos = rb_str_index(str, sub, pos);
        pos = rb_str_sublen(str, pos);
        break;
    }

    if (pos == -1) return Qnil;
    return LONG2NUM(pos);
}
            
replace(other_str) => str click to toggle source

Replaces the contents and taintedness of str with the corresponding values in other_str.

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"
 
               VALUE
rb_str_replace(VALUE str, VALUE str2)
{
    long len;
    if (str == str2) return str;

    StringValue(str2);
    len = RSTRING_LEN(str2);
    if (STR_ASSOC_P(str2)) {
        str2 = rb_str_new4(str2);
    }
    if (str_independent(str) && !STR_EMBED_P(str)) {
        xfree(RSTRING_PTR(str));
    }
    if (STR_SHARED_P(str2)) {
        STR_SET_NOEMBED(str);
        RSTRING(str)->as.heap.len = len;
        RSTRING(str)->as.heap.ptr = RSTRING_PTR(str2);
        FL_SET(str, ELTS_SHARED);
        FL_UNSET(str, STR_ASSOC);
        RSTRING(str)->as.heap.aux.shared = RSTRING(str2)->as.heap.aux.shared;
    }
    else {
        str_replace_shared(str, rb_str_new4(str2));
    }

    OBJ_INFECT(str, str2);
    rb_enc_cr_str_exact_copy(str, str2);
    return str;
}
            
insert(index, other_str) => str click to toggle source

Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is insert aString so that it starts at the given index.

"abcd".insert(0, 'X')    #=> "Xabcd"
"abcd".insert(3, 'X')    #=> "abcXd"
"abcd".insert(4, 'X')    #=> "abcdX"
"abcd".insert(-3, 'X')   #=> "abXcd"
"abcd".insert(-1, 'X')   #=> "abcdX"
 
               static VALUE
rb_str_insert(VALUE str, VALUE idx, VALUE str2)
{
    long pos = NUM2LONG(idx);

    if (pos == -1) {
        return rb_str_append(str, str2);
    }
    else if (pos < 0) {
        pos++;
    }
    rb_str_splice(str, pos, 0, str2);
    return str;
}
            
inspect => string click to toggle source

Returns a printable version of str, surrounded by quote marks, with special characters escaped.

str = "hello"
str[3] = "\b"
str.inspect       #=> "\"hel\\bo\""
 
               VALUE
rb_str_inspect(VALUE str)
{
    rb_encoding *enc = STR_ENC_GET(str);
    char *p, *pend;
    VALUE result = rb_str_buf_new(0);

    if (!rb_enc_asciicompat(enc)) enc = rb_usascii_encoding();
    rb_enc_associate(result, enc);
    str_cat_char(result, '"', enc);
    p = RSTRING_PTR(str); pend = RSTRING_END(str);
    while (p < pend) {
        unsigned int c, cc;
        int n;

        n = rb_enc_precise_mbclen(p, pend, enc);
        if (!MBCLEN_CHARFOUND_P(n)) {
            p++;
            n = 1;
            goto escape_codepoint;
        }
        n = MBCLEN_CHARFOUND_LEN(n);

        c = rb_enc_codepoint(p, pend, enc);
        n = rb_enc_codelen(c, enc);

        p += n;
        if (c == '"'|| c == '\\' ||
            (c == '#' &&
             p < pend &&
             MBCLEN_CHARFOUND_P(rb_enc_precise_mbclen(p,pend,enc)) &&
             (cc = rb_enc_codepoint(p,pend,enc),
              (cc == '$' || cc == '@' || cc == '{')))) {
            prefix_escape(result, c, enc);
        }
        else if (c == '\n') {
            prefix_escape(result, 'n', enc);
        }
        else if (c == '\r') {
            prefix_escape(result, 'r', enc);
        }
        else if (c == '\t') {
            prefix_escape(result, 't', enc);
        }
        else if (c == '\f') {
            prefix_escape(result, 'f', enc);
        }
        else if (c == '\013') {
            prefix_escape(result, 'v', enc);
        }
        else if (c == '\010') {
            prefix_escape(result, 'b', enc);
        }
        else if (c == '\007') {
            prefix_escape(result, 'a', enc);
        }
        else if (c == 033) {
            prefix_escape(result, 'e', enc);
        }
        else if (rb_enc_isprint(c, enc)) {
            rb_enc_str_buf_cat(result, p-n, n, enc);
        }
        else {
            char buf[5];
            char *s;
            char *q;

          escape_codepoint:
            for (q = p-n; q < p; q++) {
                s = buf;
                sprintf(buf, "\\x%02X", *q & 0377);
                while (*s) {
                    str_cat_char(result, *s++, enc);
                }
            }
        }
    }
    str_cat_char(result, '"', enc);

    OBJ_INFECT(result, str);
    return result;
}
            
intern => symbol click to toggle source

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

'cat and dog'.to_sym   #=> :"cat and dog"
 
               VALUE
rb_str_intern(VALUE s)
{
    VALUE str = RB_GC_GUARD(s);
    ID id;

    id = rb_intern_str(str);
    return ID2SYM(id);
}
            
length => integer click to toggle source

Returns the character length of str.

 
               VALUE
rb_str_length(VALUE str)
{
    int len;

    len = str_strlen(str, STR_ENC_GET(str));
    return INT2NUM(len);
}
            
lines(separator=$/) => anEnumerator click to toggle source
lines(separator=$/) {|substr| block } => str

Returns an enumerator that gives each line in the string. If a block is given, it iterates over each line in the string.

"foo\nbar\n".lines.to_a   #=> ["foo\n", "bar\n"]
"foo\nb ar".lines.sort    #=> ["b ar", "foo\n"]
 
               static VALUE
rb_str_each_line(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    VALUE rs;
    unsigned int newline;
    char *p, *pend, *s, *ptr;
    long len, rslen; 
    VALUE line;
    int n;
    VALUE orig = str;

    if (argc == 0) {
        rs = rb_rs;
    }
    else {
        rb_scan_args(argc, argv, "01", &rs);
    }
    RETURN_ENUMERATOR(str, argc, argv);
    if (NIL_P(rs)) {
        rb_yield(str);
        return orig;
    }
    str = rb_str_new4(str);
    ptr = p = s = RSTRING_PTR(str);
    pend = p + RSTRING_LEN(str);
    len = RSTRING_LEN(str);
    StringValue(rs);
    if (rs == rb_default_rs) {
        enc = rb_enc_get(str);
        while (p < pend) {
            char *p0;

            p = memchr(p, '\n', pend - p);
            if (!p) break;
            p0 = rb_enc_left_char_head(s, p, pend, enc);
            if (!rb_enc_is_newline(p0, pend, enc)) {
                p++;
                continue;
            }
            p = p0 + rb_enc_mbclen(p0, pend, enc);
            line = rb_str_new5(str, s, p - s);
            OBJ_INFECT(line, str);
            rb_enc_cr_str_copy_for_substr(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p;
        }
        goto finish;
    }

    enc = rb_enc_check(str, rs);
    rslen = RSTRING_LEN(rs);
    if (rslen == 0) {
        newline = '\n';
    }
    else {
        newline = rb_enc_codepoint(RSTRING_PTR(rs), RSTRING_END(rs), enc);
    }

    while (p < pend) {
        unsigned int c = rb_enc_codepoint(p, pend, enc);

      again:
        n = rb_enc_codelen(c, enc);
        if (rslen == 0 && c == newline) {
            p += n;
            if (p < pend && (c = rb_enc_codepoint(p, pend, enc)) != newline) {
                goto again;
            }
            while (p < pend && rb_enc_codepoint(p, pend, enc) == newline) {
                p += n;
            }
            p -= n;
        }
        if (c == newline &&
            (rslen <= 1 || memcmp(RSTRING_PTR(rs), p, rslen) == 0)) {
            line = rb_str_new5(str, s, p - s + (rslen ? rslen : n));
            OBJ_INFECT(line, str);
            rb_enc_cr_str_copy_for_substr(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p + (rslen ? rslen : n);
        }
        p += n;
    }

  finish:
    if (s != pend) {
        line = rb_str_new5(str, s, pend - s);
        OBJ_INFECT(line, str);
        rb_enc_cr_str_copy_for_substr(line, str);
        rb_yield(line);
    }

    return orig;
}
            
ljust(integer, padstr=' ') => new_str click to toggle source

If integer is greater than the length of str, returns a new String of length integer with str left justified and padded with padstr; otherwise, returns str.

"hello".ljust(4)            #=> "hello"
"hello".ljust(20)           #=> "hello               "
"hello".ljust(20, '1234')   #=> "hello123412341234123"
 
               static VALUE
rb_str_ljust(int argc, VALUE *argv, VALUE str)
{
    return rb_str_justify(argc, argv, str, 'l');
}
            
lstrip => new_str click to toggle source

Returns a copy of str with leading whitespace removed. See also String#rstrip and String#strip.

"  hello  ".lstrip   #=> "hello  "
"hello".lstrip       #=> "hello"
 
               static VALUE
rb_str_lstrip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_lstrip_bang(str);
    return str;
}
            
lstrip! => self or nil click to toggle source

Removes leading whitespace from str, returning nil if no change was made. See also String#rstrip! and String#strip!.

"  hello  ".lstrip   #=> "hello  "
"hello".lstrip!      #=> nil
 
               static VALUE
rb_str_lstrip_bang(VALUE str)
{
    rb_encoding *enc;
    char *s, *t, *e;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    s = RSTRING_PTR(str);
    if (!s || RSTRING_LEN(str) == 0) return Qnil;
    e = t = RSTRING_END(str);
    /* remove spaces at head */
    while (s < e) {
        unsigned int cc = rb_enc_codepoint(s, e, enc);
        
        if (!rb_enc_isspace(cc, enc)) break;
        s += rb_enc_codelen(cc, enc);
    }

    if (s > RSTRING_PTR(str)) {
        STR_SET_LEN(str, t-s);
        memmove(RSTRING_PTR(str), s, RSTRING_LEN(str));
        RSTRING_PTR(str)[RSTRING_LEN(str)] = '\0';
        return str;
    }
    return Qnil;
}
            
match(pattern) => matchdata or nil click to toggle source

Converts pattern to a Regexp (if it isn't already one), then invokes its match method on str. If the second parameter is present, it specifies the position in the string to begin the search.

'hello'.match('(.)\1')      #=> #<MatchData "ll" 1:"l">
'hello'.match('(.)\1')[0]   #=> "ll"
'hello'.match(/(.)\1/)[0]   #=> "ll"
'hello'.match('xx')         #=> nil

If a block is given, invoke the block with MatchData if match succeed, so that you can write

str.match(pat) {|m| ...}

instead of

if m = str.match(pat)
  ...
end

The return value is a value from block execution in this case.

 
               static VALUE
rb_str_match_m(int argc, VALUE *argv, VALUE str)
{
    VALUE re, result;
    if (argc < 1)
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    re = argv[0];
    argv[0] = str;
    result = rb_funcall2(get_pat(re, 0), rb_intern("match"), argc, argv);
    if (!NIL_P(result) && rb_block_given_p()) {
        return rb_yield(result);
    }
    return result;
}
            
next => new_str click to toggle source

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.

If the increment generates a “carry,'' the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

"abcd".succ        #=> "abce"
"THX1138".succ     #=> "THX1139"
"<<koala>>".succ   #=> "<<koalb>>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"
 
               VALUE
rb_str_succ(VALUE orig)
{
    rb_encoding *enc;
    VALUE str;
    char *sbeg, *s, *e, *last_alnum = 0;
    int c = -1;
    long l;
    char carry[ONIGENC_CODE_TO_MBC_MAXLEN] = "\1";
    int carry_pos = 0, carry_len = 1;
    enum neighbor_char neighbor = NEIGHBOR_FOUND;

    str = rb_str_new5(orig, RSTRING_PTR(orig), RSTRING_LEN(orig));
    rb_enc_cr_str_copy_for_substr(str, orig);
    OBJ_INFECT(str, orig);
    if (RSTRING_LEN(str) == 0) return str;

    enc = STR_ENC_GET(orig);
    sbeg = RSTRING_PTR(str);
    s = e = sbeg + RSTRING_LEN(str);

    while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) {
        if (neighbor == NEIGHBOR_NOT_CHAR && last_alnum) {
            if (ISALPHA(*last_alnum) ? ISDIGIT(*s) :
                ISDIGIT(*last_alnum) ? ISALPHA(*s) : 0) {
                s = last_alnum;
                break;
            }
        }
        if ((l = rb_enc_precise_mbclen(s, e, enc)) <= 0) continue;
        neighbor = enc_succ_alnum_char(s, l, enc, carry);
        switch (neighbor) {
          case NEIGHBOR_NOT_CHAR:
            continue;
          case NEIGHBOR_FOUND:
            return str;
          case NEIGHBOR_WRAPPED:
            last_alnum = s;
            break;
        }
        c = 1;
        carry_pos = s - sbeg;
        carry_len = l;
    }
    if (c == -1) {              /* str contains no alnum */
        s = e;
        while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) {
            enum neighbor_char neighbor;
            if ((l = rb_enc_precise_mbclen(s, e, enc)) <= 0) continue;
            neighbor = enc_succ_char(s, l, enc);
            if (neighbor == NEIGHBOR_FOUND)
                return str;
            if (rb_enc_precise_mbclen(s, s+l, enc) != l) {
                /* wrapped to \0...\0.  search next valid char. */
                enc_succ_char(s, l, enc);
            }
            if (!rb_enc_asciicompat(enc)) {
                MEMCPY(carry, s, char, l);
                carry_len = l;
            }
            carry_pos = s - sbeg;
        }
    }
    RESIZE_CAPA(str, RSTRING_LEN(str) + carry_len);
    s = RSTRING_PTR(str) + carry_pos;
    memmove(s + carry_len, s, RSTRING_LEN(str) - carry_pos);
    memmove(s, carry, carry_len);
    STR_SET_LEN(str, RSTRING_LEN(str) + carry_len);
    RSTRING_PTR(str)[RSTRING_LEN(str)] = '\0';
    rb_enc_str_coderange(str);
    return str;
}
            
next! => str click to toggle source

Equivalent to String#succ, but modifies the receiver in place.

 
               static VALUE
rb_str_succ_bang(VALUE str)
{
    rb_str_shared_replace(str, rb_str_succ(str));

    return str;
}
            
oct => integer click to toggle source

Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number. Returns 0 if the conversion fails.

"123".oct       #=> 83
"-377".oct      #=> -255
"bad".oct       #=> 0
"0377bad".oct   #=> 255
 
               static VALUE
rb_str_oct(VALUE str)
{
    rb_encoding *enc = rb_enc_get(str);

    if (!rb_enc_asciicompat(enc)) {
        rb_raise(rb_eEncCompatError, "ASCII incompatible encoding: %s", rb_enc_name(enc));
    }
    return rb_str_to_inum(str, -8, Qfalse);
}
            
ord => integer click to toggle source

Return the Integer ordinal of a one-character string.

"a".ord         #=> 97
 
               VALUE
rb_str_ord(VALUE s)
{
    unsigned int c;

    c = rb_enc_codepoint(RSTRING_PTR(s), RSTRING_END(s), STR_ENC_GET(s));
    return UINT2NUM(c);
}
            
partition(sep) => [head, sep, tail] click to toggle source
partition(regexp) => [head, match, tail]

Searches sep or pattern (regexp) in the string and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.

"hello".partition("l")         #=> ["he", "l", "lo"]
"hello".partition("x")         #=> ["hello", "", ""]
"hello".partition(/.l/)        #=> ["h", "el", "lo"]
 
               static VALUE
rb_str_partition(VALUE str, VALUE sep)
{
    long pos;
    int regex = Qfalse;

    if (TYPE(sep) == T_REGEXP) {
        pos = rb_reg_search(sep, str, 0, 0);
        regex = Qtrue;
    }
    else {
        VALUE tmp;

        tmp = rb_check_string_type(sep);
        if (NIL_P(tmp)) {
            rb_raise(rb_eTypeError, "type mismatch: %s given",
                     rb_obj_classname(sep));
        }
        sep = tmp;
        pos = rb_str_index(str, sep, 0);
    }
    if (pos < 0) {
      failed:
        return rb_ary_new3(3, str, rb_str_new(0,0),rb_str_new(0,0));
    }
    if (regex) {
        sep = rb_str_subpat(str, sep, 0);
        if (pos == 0 && RSTRING_LEN(sep) == 0) goto failed;
    }
    return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
                          sep,
                          rb_str_subseq(str, pos+RSTRING_LEN(sep),
                                             RSTRING_LEN(str)-pos-RSTRING_LEN(sep)));
}
            
replace(other_str) => str click to toggle source

Replaces the contents and taintedness of str with the corresponding values in other_str.

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"
 
               VALUE
rb_str_replace(VALUE str, VALUE str2)
{
    long len;
    if (str == str2) return str;

    StringValue(str2);
    len = RSTRING_LEN(str2);
    if (STR_ASSOC_P(str2)) {
        str2 = rb_str_new4(str2);
    }
    if (str_independent(str) && !STR_EMBED_P(str)) {
        xfree(RSTRING_PTR(str));
    }
    if (STR_SHARED_P(str2)) {
        STR_SET_NOEMBED(str);
        RSTRING(str)->as.heap.len = len;
        RSTRING(str)->as.heap.ptr = RSTRING_PTR(str2);
        FL_SET(str, ELTS_SHARED);
        FL_UNSET(str, STR_ASSOC);
        RSTRING(str)->as.heap.aux.shared = RSTRING(str2)->as.heap.aux.shared;
    }
    else {
        str_replace_shared(str, rb_str_new4(str2));
    }

    OBJ_INFECT(str, str2);
    rb_enc_cr_str_exact_copy(str, str2);
    return str;
}
            
reverse => new_str click to toggle source

Returns a new string with the characters from str in reverse order.

"stressed".reverse   #=> "desserts"
 
               static VALUE
rb_str_reverse(VALUE str)
{
    rb_encoding *enc;
    VALUE rev;
    char *s, *e, *p;
    int single = 1;

    if (RSTRING_LEN(str) <= 1) return rb_str_dup(str);
    enc = STR_ENC_GET(str);
    rev = rb_str_new5(str, 0, RSTRING_LEN(str));
    s = RSTRING_PTR(str); e = RSTRING_END(str);
    p = RSTRING_END(rev);

    if (RSTRING_LEN(str) > 1) {
        if (single_byte_optimizable(str)) {
            while (s < e) {
                *--p = *s++;
            }
        }
        else {
            while (s < e) {
                int clen = rb_enc_mbclen(s, e, enc);

                if (clen > 1 || (*s & 0x80)) single = 0;
                p -= clen;
                memcpy(p, s, clen);
                s += clen;
            }
        }
    }
    STR_SET_LEN(rev, RSTRING_LEN(str));
    OBJ_INFECT(rev, str);
    if (ENC_CODERANGE(str) == ENC_CODERANGE_UNKNOWN) {
        if (single) {
            ENC_CODERANGE_SET(str, ENC_CODERANGE_7BIT);
        }
        else {
            ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID);
        }
    }
    rb_enc_cr_str_copy_for_substr(rev, str);

    return rev;
}
            
reverse! => str click to toggle source

Reverses str in place.

 
               static VALUE
rb_str_reverse_bang(VALUE str)
{
    if (RSTRING_LEN(str) > 1) {
        if (single_byte_optimizable(str)) {
            char *s, *e, c;

            str_modify_keep_cr(str);
            s = RSTRING_PTR(str);
            e = RSTRING_END(str) - 1;
            while (s < e) {
                c = *s;
                *s++ = *e;
                *e-- = c;
            }
        }
        else {
            rb_str_shared_replace(str, rb_str_reverse(str));
        }
    }
    return str;
}
            
rindex(substring [, fixnum]) => fixnum or nil click to toggle source
rindex(regexp [, fixnum]) => fixnum or nil

Returns the index of the last occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search—characters beyond this point will not be considered.

"hello".rindex('e')             #=> 1
"hello".rindex('l')             #=> 3
"hello".rindex('a')             #=> nil
"hello".rindex(?e)              #=> 1
"hello".rindex(/[aeiou]/, -2)   #=> 1
 
               static VALUE
rb_str_rindex_m(int argc, VALUE *argv, VALUE str)
{
    VALUE sub;
    VALUE vpos;
    rb_encoding *enc = STR_ENC_GET(str);
    long pos, len = str_strlen(str, enc);

    if (rb_scan_args(argc, argv, "11", &sub, &vpos) == 2) {
        pos = NUM2LONG(vpos);
        if (pos < 0) {
            pos += len;
            if (pos < 0) {
                if (TYPE(sub) == T_REGEXP) {
                    rb_backref_set(Qnil);
                }
                return Qnil;
            }
        }
        if (pos > len) pos = len;
    }
    else {
        pos = len;
    }

    switch (TYPE(sub)) {
      case T_REGEXP:
        /* enc = rb_get_check(str, sub); */
        pos = str_offset(RSTRING_PTR(str), RSTRING_END(str), pos,
                         STR_ENC_GET(str), single_byte_optimizable(str));

        if (!RREGEXP(sub)->ptr || RREGEXP_SRC_LEN(sub)) {
            pos = rb_reg_search(sub, str, pos, 1);
            pos = rb_str_sublen(str, pos);
        }
        if (pos >= 0) return LONG2NUM(pos);
        break;

      default: {
        VALUE tmp;

        tmp = rb_check_string_type(sub);
        if (NIL_P(tmp)) {
            rb_raise(rb_eTypeError, "type mismatch: %s given",
                     rb_obj_classname(sub));
        }
        sub = tmp;
      }
        /* fall through */
      case T_STRING:
        pos = rb_str_rindex(str, sub, pos);
        if (pos >= 0) return LONG2NUM(pos);
        break;
    }
    return Qnil;
}
            
rjust(integer, padstr=' ') => new_str click to toggle source

If integer is greater than the length of str, returns a new String of length integer with str right justified and padded with padstr; otherwise, returns str.

"hello".rjust(4)            #=> "hello"
"hello".rjust(20)           #=> "               hello"
"hello".rjust(20, '1234')   #=> "123412341234123hello"
 
               static VALUE
rb_str_rjust(int argc, VALUE *argv, VALUE str)
{
    return rb_str_justify(argc, argv, str, 'r');
}
            
rpartition(sep) => [head, sep, tail] click to toggle source
rpartition(regexp) => [head, match, tail]

Searches sep or pattern (regexp) in the string from the end of the string, and returns the part before it, the match, and the part after it. If it is not found, returns two empty strings and str.

"hello".rpartition("l")         #=> ["hel", "l", "o"]
"hello".rpartition("x")         #=> ["", "", "hello"]
"hello".rpartition(/.l/)        #=> ["he", "ll", "o"]
 
               static VALUE
rb_str_rpartition(VALUE str, VALUE sep)
{
    long pos = RSTRING_LEN(str);
    int regex = Qfalse;

    if (TYPE(sep) == T_REGEXP) {
        pos = rb_reg_search(sep, str, pos, 1);
        regex = Qtrue;
    }
    else {
        VALUE tmp;

        tmp = rb_check_string_type(sep);
        if (NIL_P(tmp)) {
            rb_raise(rb_eTypeError, "type mismatch: %s given",
                     rb_obj_classname(sep));
        }
        sep = tmp;
        pos = rb_str_sublen(str, pos);
        pos = rb_str_rindex(str, sep, pos);
    }
    if (pos < 0) {
        return rb_ary_new3(3, rb_str_new(0,0),rb_str_new(0,0), str);
    }
    if (regex) {
        sep = rb_reg_nth_match(0, rb_backref_get());
    }
    return rb_ary_new3(3, rb_str_substr(str, 0, pos),
                          sep,
                          rb_str_substr(str,pos+str_strlen(sep,STR_ENC_GET(sep)),RSTRING_LEN(str)));
}
            
rstrip => new_str click to toggle source

Returns a copy of str with trailing whitespace removed. See also String#lstrip and String#strip.

"  hello  ".rstrip   #=> "  hello"
"hello".rstrip       #=> "hello"
 
               static VALUE
rb_str_rstrip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_rstrip_bang(str);
    return str;
}
            
rstrip! => self or nil click to toggle source

Removes trailing whitespace from str, returning nil if no change was made. See also String#lstrip! and String#strip!.

"  hello  ".rstrip   #=> "  hello"
"hello".rstrip!      #=> nil
 
               static VALUE
rb_str_rstrip_bang(VALUE str)
{
    rb_encoding *enc;
    char *s, *t, *e;

    enc = STR_ENC_GET(str);
    rb_str_check_dummy_enc(enc);
    s = RSTRING_PTR(str);
    if (!s || RSTRING_LEN(str) == 0) return Qnil;
    t = e = RSTRING_END(str);

    /* remove trailing spaces or '\0's */
    if (single_byte_optimizable(str)) {
        unsigned char c;
        while (s < t && ((c = *(t-1)) == '\0' || rb_enc_isspace(c, enc))) t--;
    }
    else {
        char *tp;

        while ((tp = rb_enc_prev_char(s, t, e, enc)) != NULL) {
            unsigned int c = rb_enc_codepoint(tp, e, enc);
            if (c && !rb_enc_isspace(c, enc)) break;
            t = tp;
        }
    }
    if (t < e) {
        int len = t-RSTRING_PTR(str);

        str_modify_keep_cr(str);
        STR_SET_LEN(str, len);
        RSTRING_PTR(str)[len] = '\0';
        return str;
    }
    return Qnil;
}
            
scan(pattern) => array click to toggle source
scan(pattern) {|match, ...| block } => str

Both forms iterate through str, matching the pattern (which may be a Regexp or a String). For each match, a result is generated and either added to the result array or passed to the block. If the pattern contains no groups, each individual result consists of the matched string, $&. If the pattern contains groups, each individual result is itself an array containing one entry per group.

a = "cruel world"
a.scan(/\w+/)        #=> ["cruel", "world"]
a.scan(/.../)        #=> ["cru", "el ", "wor"]
a.scan(/(...)/)      #=> [["cru"], ["el "], ["wor"]]
a.scan(/(..)(..)/)   #=> [["cr", "ue"], ["l ", "wo"]]

And the block form:

a.scan(/\w+/) {|w| print "<<#{w}>> " }
print "\n"
a.scan(/(.)(.)/) {|x,y| print y, x }
print "\n"

produces:

<<cruel>> <<world>>
rceu lowlr
 
               static VALUE
rb_str_scan(VALUE str, VALUE pat)
{
    VALUE result;
    long start = 0;
    long last = -1, prev = 0;
    char *p = RSTRING_PTR(str); long len = RSTRING_LEN(str);

    pat = get_pat(pat, 1);
    if (!rb_block_given_p()) {
        VALUE ary = rb_ary_new();

        while (!NIL_P(result = scan_once(str, pat, &start))) {
            last = prev;
            prev = start;
            rb_ary_push(ary, result);
        }
        if (last >= 0) rb_reg_search(pat, str, last, 0);
        return ary;
    }

    while (!NIL_P(result = scan_once(str, pat, &start))) {
        last = prev;
        prev = start;
        rb_yield(result);
        str_mod_check(str, p, len);
    }
    if (last >= 0) rb_reg_search(pat, str, last, 0);
    return str;
}
            
setbyte(index, int) => int click to toggle source

modifies the indexth byte as int.

 
               static VALUE
rb_str_setbyte(VALUE str, VALUE index, VALUE value)
{
    long pos = NUM2LONG(index);
    int byte = NUM2INT(value);

    rb_str_modify(str);

    if (pos < -RSTRING_LEN(str) || RSTRING_LEN(str) <= pos)
        rb_raise(rb_eIndexError, "index %ld out of string", pos);
    if (pos < 0)
        pos += RSTRING_LEN(str);

    RSTRING_PTR(str)[pos] = byte;

    return value;
}
            
size => integer click to toggle source

Returns the character length of str.

 
               VALUE
rb_str_length(VALUE str)
{
    int len;

    len = str_strlen(str, STR_ENC_GET(str));
    return INT2NUM(len);
}
            
slice(fixnum) => new_str or nil click to toggle source
slice(fixnum, fixnum) => new_str or nil
slice(range) => new_str or nil
slice(regexp) => new_str or nil
slice(regexp, fixnum) => new_str or nil
slice(other_str) => new_str or nil

Element Reference—If passed a single Fixnum, returns a substring of one character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end.

If a Regexp is supplied, the matching portion of str is returned. If a numeric parameter follows the regular expression, that component of the MatchData is returned instead. If a String is given, that string is returned if it occurs in str. In both cases, nil is returned if there is no match.

a = "hello there"
a[1]                   #=> "e"
a[1,3]                 #=> "ell"
a[1..3]                #=> "ell"
a[-3,2]                #=> "er"
a[-4..-2]              #=> "her"
a[12..-1]              #=> nil
a[-2..-4]              #=> ""
a[/[aeiou](.)\1/]      #=> "ell"
a[/[aeiou](.)\1/, 0]   #=> "ell"
a[/[aeiou](.)\1/, 1]   #=> "l"
a[/[aeiou](.)\1/, 2]   #=> nil
a["lo"]                #=> "lo"
a["bye"]               #=> nil
 
               static VALUE
rb_str_aref_m(int argc, VALUE *argv, VALUE str)
{
    if (argc == 2) {
        if (TYPE(argv[0]) == T_REGEXP) {
            return rb_str_subpat(str, argv[0], NUM2INT(argv[1]));
        }
        return rb_str_substr(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]));
    }
    if (argc != 1) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    return rb_str_aref(str, argv[0]);
}
            
slice!(fixnum) => fixnum or nil click to toggle source
slice!(fixnum, fixnum) => new_str or nil
slice!(range) => new_str or nil
slice!(regexp) => new_str or nil
slice!(other_str) => new_str or nil

Deletes the specified portion from str, and returns the portion deleted.

string = "this is a string"
string.slice!(2)        #=> "i"
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
string                  #=> "thing"
 
               static VALUE
rb_str_slice_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE result;
    VALUE buf[3];
    int i;

    if (argc < 1 || 2 < argc) {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 1)", argc);
    }
    for (i=0; i<argc; i++) {
        buf[i] = argv[i];
    }
    str_modify_keep_cr(str);
    buf[i] = rb_str_new(0,0);
    result = rb_str_aref_m(argc, buf, str);
    if (!NIL_P(result)) {
        rb_str_aset_m(argc+1, buf, str);
    }
    return result;
}
            
split(pattern=$;, [limit]) => anArray click to toggle source

Divides str into substrings based on a delimiter, returning an array of these substrings.

If pattern is a String, then its contents are used as the delimiter when splitting str. If pattern is a single space, str is split on whitespace, with leading whitespace and runs of contiguous whitespace characters ignored.

If pattern is a Regexp, str is divided where the pattern matches. Whenever the pattern matches a zero-length string, str is split into individual characters. If pattern contains groups, the respective matches will be returned in the array as well.

If pattern is omitted, the value of $; is used. If $; is nil (which is the default), str is split on whitespace as if ` ' were specified.

If the limit parameter is omitted, trailing null fields are suppressed. If limit is a positive number, at most that number of fields will be returned (if limit is 1, the entire string is returned as the only entry in an array). If negative, there is no limit to the number of fields returned, and trailing null fields are not suppressed.

" now's  the time".split        #=> ["now's", "the", "time"]
" now's  the time".split(' ')   #=> ["now's", "the", "time"]
" now's  the time".split(/ /)   #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//)               #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3)            #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*})         #=> ["h", "i", "m", "o", "m"]

"mellow yellow".split("ello")   #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',')         #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4)      #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4)     #=> ["1", "2", "", "3", "4", "", ""]
 
               static VALUE
rb_str_split_m(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    VALUE spat;
    VALUE limit;
    enum {awk, string, regexp} split_type;
    long beg, end, i = 0;
    int lim = 0;
    VALUE result, tmp;

    if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) {
        lim = NUM2INT(limit);
        if (lim <= 0) limit = Qnil;
        else if (lim == 1) {
            if (RSTRING_LEN(str) == 0)
                return rb_ary_new2(0);
            return rb_ary_new3(1, str);
        }
        i = 1;
    }

    enc = STR_ENC_GET(str);
    if (NIL_P(spat)) {
        if (!NIL_P(rb_fs)) {
            spat = rb_fs;
            goto fs_set;
        }
        split_type = awk;
    }
    else {
      fs_set:
        if (TYPE(spat) == T_STRING) {
            rb_encoding *enc2 = STR_ENC_GET(spat);

            split_type = string;
            if (RSTRING_LEN(spat) == 0) {
                /* Special case - split into chars */
                spat = rb_reg_regcomp(spat);
                split_type = regexp;
            }
            else if (rb_enc_asciicompat(enc2) == 1) {
                if (RSTRING_LEN(spat) == 1 && RSTRING_PTR(spat)[0] == ' '){
                    split_type = awk;
                }
            }
            else {
                int l;
                if (rb_enc_ascget(RSTRING_PTR(spat), RSTRING_END(spat), &l, enc2) == ' ' &&
                    RSTRING_LEN(spat) == l) {
                    split_type = awk;
                }
            }
        }
        else {
            spat = get_pat(spat, 1);
            split_type = regexp;
        }
    }

    result = rb_ary_new();
    beg = 0;
    if (split_type == awk) {
        char *ptr = RSTRING_PTR(str);
        char *eptr = RSTRING_END(str);
        char *bptr = ptr;
        int skip = 1;
        unsigned int c;

        end = beg;
        while (ptr < eptr) {
            c = rb_enc_codepoint(ptr, eptr, enc);
            ptr += rb_enc_mbclen(ptr, eptr, enc);
            if (skip) {
                if (rb_enc_isspace(c, enc)) {
                    beg = ptr - bptr;
                }
                else {
                    end = ptr - bptr;
                    skip = 0;
                    if (!NIL_P(limit) && lim <= i) break;
                }
            }
            else {
                if (rb_enc_isspace(c, enc)) {
                    rb_ary_push(result, rb_str_subseq(str, beg, end-beg));
                    skip = 1;
                    beg = ptr - bptr;
                    if (!NIL_P(limit)) ++i;
                }
                else {
                    end = ptr - bptr;
                }
            }
        }
    }
    else if (split_type == string) {
        char *ptr = RSTRING_PTR(str);
        char *eptr = RSTRING_END(str);
        char *sptr = RSTRING_PTR(spat);
        int slen = RSTRING_LEN(spat);

        if (is_broken_string(str)) {
            rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(STR_ENC_GET(str)));
        }
        if (is_broken_string(spat)) {
            rb_raise(rb_eArgError, "invalid byte sequence in %s", rb_enc_name(STR_ENC_GET(spat)));
        }
        enc = rb_enc_check(str, spat);
        while (ptr < eptr &&
               (end = rb_memsearch(sptr, slen, ptr, eptr - ptr, enc)) >= 0) {
            /* Check we are at the start of a char */
            char *t = rb_enc_right_char_head(ptr, ptr + end, eptr, enc);
            if (t != ptr + end) {
                ptr = t;
                continue;
            }
            rb_ary_push(result, rb_str_subseq(str, ptr - RSTRING_PTR(str), end));
            ptr += end + slen;
            if (!NIL_P(limit) && lim <= ++i) break;
        }
        beg = ptr - RSTRING_PTR(str);
    }
    else {
        long start = beg;
        long idx;
        int last_null = 0;
        struct re_registers *regs;

        while ((end = rb_reg_search(spat, str, start, 0)) >= 0) {
            regs = RMATCH_REGS(rb_backref_get());
            if (start == end && BEG(0) == END(0)) {
                if (!RSTRING_PTR(str)) {
                    rb_ary_push(result, rb_str_new("", 0));
                    break;
                }
                else if (last_null == 1) {
                    rb_ary_push(result, rb_str_subseq(str, beg,
                                                      rb_enc_mbclen(RSTRING_PTR(str)+beg,
                                                                    RSTRING_END(str),
                                                                    enc)));
                    beg = start;
                }
                else {
                    if (RSTRING_PTR(str)+start == RSTRING_END(str))
                        start++;
                    else
                        start += rb_enc_mbclen(RSTRING_PTR(str)+start,RSTRING_END(str),enc);
                    last_null = 1;
                    continue;
                }
            }
            else {
                rb_ary_push(result, rb_str_subseq(str, beg, end-beg));
                beg = start = END(0);
            }
            last_null = 0;

            for (idx=1; idx < regs->num_regs; idx++) {
                if (BEG(idx) == -1) continue;
                if (BEG(idx) == END(idx))
                    tmp = rb_str_new5(str, 0, 0);
                else
                    tmp = rb_str_subseq(str, BEG(idx), END(idx)-BEG(idx));
                rb_ary_push(result, tmp);
            }
            if (!NIL_P(limit) && lim <= ++i) break;
        }
    }
    if (RSTRING_LEN(str) > 0 && (!NIL_P(limit) || RSTRING_LEN(str) > beg || lim < 0)) {
        if (RSTRING_LEN(str) == beg)
            tmp = rb_str_new5(str, 0, 0);
        else
            tmp = rb_str_subseq(str, beg, RSTRING_LEN(str)-beg);
        rb_ary_push(result, tmp);
    }
    if (NIL_P(limit) && lim == 0) {
        long len;
        while ((len = RARRAY_LEN(result)) > 0 &&
               (tmp = RARRAY_PTR(result)[len-1], RSTRING_LEN(tmp) == 0))
            rb_ary_pop(result);
    }

    return result;
}
            
squeeze([other_str]*) => new_str click to toggle source

Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character.

"yellow moon".squeeze                  #=> "yelow mon"
"  now   is  the".squeeze(" ")         #=> " now is the"
"putters shoot balls".squeeze("m-z")   #=> "puters shot balls"
 
               static VALUE
rb_str_squeeze(int argc, VALUE *argv, VALUE str)
{
    str = rb_str_dup(str);
    rb_str_squeeze_bang(argc, argv, str);
    return str;
}
            
squeeze!([other_str]*) => str or nil click to toggle source

Squeezes str in place, returning either str, or nil if no changes were made.

 
               static VALUE
rb_str_squeeze_bang(int argc, VALUE *argv, VALUE str)
{
    char squeez[256];
    rb_encoding *enc = 0;
    VALUE del = 0, nodel = 0;
    char *s, *send, *t;
    int save, modify = 0;
    int i;
    int ascompat, singlebyte = single_byte_optimizable(str);

    if (argc == 0) {
        enc = STR_ENC_GET(str);
    }
    else {
        for (i=0; i<argc; i++) {
            VALUE s = argv[i];

            StringValue(s);
            enc = rb_enc_check(str, s);
            if (singlebyte && !single_byte_optimizable(s))
                singlebyte = 0;
            tr_setup_table(s, squeez, i==0, &del, &nodel, enc);
        }
    }

    str_modify_keep_cr(str);
    s = t = RSTRING_PTR(str);
    if (!s || RSTRING_LEN(str) == 0) return Qnil;
    send = RSTRING_END(str);
    save = -1;
    ascompat = rb_enc_asciicompat(enc);

    if (singlebyte) {
        while (s < send) {
            unsigned int c = *(unsigned char*)s++;
            if (c != save || (argc > 0 && !squeez[c])) {
                *t++ = save = c;
            }
        }
    } else {
        while (s < send) {
            unsigned int c;
            int clen;

            if (ascompat && (c = *(unsigned char*)s) < 0x80) {
                if (c != save || (argc > 0 && !squeez[c])) {
                    *t++ = save = c;
                }
                s++;
            }
            else {
                c = rb_enc_codepoint(s, send, enc);
                clen = rb_enc_codelen(c, enc);

                if (c != save || (argc > 0 && !tr_find(c, squeez, del, nodel))) {
                    if (t != s) rb_enc_mbcput(c, t, enc);
                    save = c;
                    t += clen;
                }
                s += clen;
            }
        }
    }

    *t = '\0';
    if (t - RSTRING_PTR(str) != RSTRING_LEN(str)) {
        STR_SET_LEN(str, t - RSTRING_PTR(str));
        modify = 1;
    }

    if (modify) return str;
    return Qnil;
}
            
start_with?([prefix]+) => true or false click to toggle source

Returns true if str starts with the prefix given.

 
               static VALUE
rb_str_start_with(int argc, VALUE *argv, VALUE str)
{
    int i;

    for (i=0; i<argc; i++) {
        VALUE tmp = rb_check_string_type(argv[i]);
        if (NIL_P(tmp)) continue;
        rb_enc_check(str, tmp);
        if (RSTRING_LEN(str) < RSTRING_LEN(tmp)) continue;
        if (memcmp(RSTRING_PTR(str), RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0)
            return Qtrue;
    }
    return Qfalse;
}
            
strip => new_str click to toggle source

Returns a copy of str with leading and trailing whitespace removed.

"    hello    ".strip   #=> "hello"
"\tgoodbye\r\n".strip   #=> "goodbye"
 
               static VALUE
rb_str_strip(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_strip_bang(str);
    return str;
}
            
strip! => str or nil click to toggle source

Removes leading and trailing whitespace from str. Returns nil if str was not altered.

 
               static VALUE
rb_str_strip_bang(VALUE str)
{
    VALUE l = rb_str_lstrip_bang(str);
    VALUE r = rb_str_rstrip_bang(str);

    if (NIL_P(l) && NIL_P(r)) return Qnil;
    return str;
}
            
sub(pattern, replacement) => new_str click to toggle source
sub(pattern) {|match| block } => new_str

Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but '\d' will match a backslash followed by a 'd').

If the method call specifies replacement, special variables such as $& will not be useful, as substitution into the string occurs before the pattern match starts. However, the sequences \1, \2, \k<group_name>, etc., may be used.

In the block form, the current match string is passed in as a parameter, and variables such as $1, $2, $`, $&, and $' will be set appropriately. The value returned by the block will be substituted for the match on each call.

The result inherits any tainting in the original string or any supplied replacement string.

"hello".sub(/[aeiou]/, '*')                  #=> "h*llo"
"hello".sub(/([aeiou])/, '<\1>')             #=> "h<e>llo"
"hello".sub(/./) {|s| s[0].ord.to_s + ' ' }  #=> "104 ello"
"hello".sub(/(?<foo>[aeiou])/, '*\k<foo>*')  #=> "h*e*llo"
 
               static VALUE
rb_str_sub(int argc, VALUE *argv, VALUE str)
{
    str = rb_str_dup(str);
    rb_str_sub_bang(argc, argv, str);
    return str;
}
            
sub!(pattern, replacement) => str or nil click to toggle source
sub!(pattern) {|match| block } => str or nil

Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed.

 
               static VALUE
rb_str_sub_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE pat, repl, hash = Qnil;
    int iter = 0;
    int tainted = 0;
    int untrusted = 0;
    long plen;

    if (argc == 1 && rb_block_given_p()) {
        iter = 1;
    }
    else if (argc == 2) {
        repl = argv[1];
        hash = rb_check_convert_type(argv[1], T_HASH, "Hash", "to_hash");
        if (NIL_P(hash)) {
            StringValue(repl);
        }
        if (OBJ_TAINTED(repl)) tainted = 1;
        if (OBJ_UNTRUSTED(repl)) untrusted = 1;
    }
    else {
        rb_raise(rb_eArgError, "wrong number of arguments (%d for 2)", argc);
    }

    pat = get_pat(argv[0], 1);
    if (rb_reg_search(pat, str, 0, 0) >= 0) {
        rb_encoding *enc;
        int cr = ENC_CODERANGE(str);
        VALUE match = rb_backref_get();
        struct re_registers *regs = RMATCH_REGS(match);
        long beg0 = BEG(0);
        long end0 = END(0);

        if (iter || !NIL_P(hash)) {
            char *p = RSTRING_PTR(str); long len = RSTRING_LEN(str);

            if (iter) {
                repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
            }
            else {
                repl = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0));
                repl = rb_obj_as_string(repl);
            }
            str_mod_check(str, p, len);
            str_frozen_check(str);
        }
        else {
            repl = rb_reg_regsub(repl, str, regs, pat);
        }
        enc = rb_enc_compatible(str, repl);
        if (!enc) {
            rb_encoding *str_enc = STR_ENC_GET(str);
            if (coderange_scan(RSTRING_PTR(str), beg0, str_enc) != ENC_CODERANGE_7BIT ||
                coderange_scan(RSTRING_PTR(str)+end0,
                               RSTRING_LEN(str)-end0, str_enc) != ENC_CODERANGE_7BIT) {
                rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s",
                         rb_enc_name(str_enc),
                         rb_enc_name(STR_ENC_GET(repl)));
            }
            enc = STR_ENC_GET(repl);
        }
        rb_str_modify(str);
        rb_enc_associate(str, enc);
        if (OBJ_TAINTED(repl)) tainted = 1;
        if (OBJ_UNTRUSTED(repl)) untrusted = 1;
        if (ENC_CODERANGE_UNKNOWN < cr && cr < ENC_CODERANGE_BROKEN) {
            int cr2 = ENC_CODERANGE(repl);
            if (cr2 == ENC_CODERANGE_BROKEN ||
                (cr == ENC_CODERANGE_VALID && cr2 == ENC_CODERANGE_7BIT))
                cr = ENC_CODERANGE_UNKNOWN;
            else
                cr = cr2;
        }
        plen = end0 - beg0;
        if (RSTRING_LEN(repl) > plen) {
            RESIZE_CAPA(str, RSTRING_LEN(str) + RSTRING_LEN(repl) - plen);
        }
        if (RSTRING_LEN(repl) != plen) {
            memmove(RSTRING_PTR(str) + beg0 + RSTRING_LEN(repl),
                    RSTRING_PTR(str) + beg0 + plen,
                    RSTRING_LEN(str) - beg0 - plen);
        }
        memcpy(RSTRING_PTR(str) + beg0,
               RSTRING_PTR(repl), RSTRING_LEN(repl));
        STR_SET_LEN(str, RSTRING_LEN(str) + RSTRING_LEN(repl) - plen);
        RSTRING_PTR(str)[RSTRING_LEN(str)] = '\0';
        ENC_CODERANGE_SET(str, cr);
        if (tainted) OBJ_TAINT(str);
        if (untrusted) OBJ_UNTRUST(str);

        return str;
    }
    return Qnil;
}
            
succ => new_str click to toggle source

Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.

If the increment generates a “carry,'' the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.

"abcd".succ        #=> "abce"
"THX1138".succ     #=> "THX1139"
"<<koala>>".succ   #=> "<<koalb>>"
"1999zzz".succ     #=> "2000aaa"
"ZZZ9999".succ     #=> "AAAA0000"
"***".succ         #=> "**+"
 
               VALUE
rb_str_succ(VALUE orig)
{
    rb_encoding *enc;
    VALUE str;
    char *sbeg, *s, *e, *last_alnum = 0;
    int c = -1;
    long l;
    char carry[ONIGENC_CODE_TO_MBC_MAXLEN] = "\1";
    int carry_pos = 0, carry_len = 1;
    enum neighbor_char neighbor = NEIGHBOR_FOUND;

    str = rb_str_new5(orig, RSTRING_PTR(orig), RSTRING_LEN(orig));
    rb_enc_cr_str_copy_for_substr(str, orig);
    OBJ_INFECT(str, orig);
    if (RSTRING_LEN(str) == 0) return str;

    enc = STR_ENC_GET(orig);
    sbeg = RSTRING_PTR(str);
    s = e = sbeg + RSTRING_LEN(str);

    while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) {
        if (neighbor == NEIGHBOR_NOT_CHAR && last_alnum) {
            if (ISALPHA(*last_alnum) ? ISDIGIT(*s) :
                ISDIGIT(*last_alnum) ? ISALPHA(*s) : 0) {
                s = last_alnum;
                break;
            }
        }
        if ((l = rb_enc_precise_mbclen(s, e, enc)) <= 0) continue;
        neighbor = enc_succ_alnum_char(s, l, enc, carry);
        switch (neighbor) {
          case NEIGHBOR_NOT_CHAR:
            continue;
          case NEIGHBOR_FOUND:
            return str;
          case NEIGHBOR_WRAPPED:
            last_alnum = s;
            break;
        }
        c = 1;
        carry_pos = s - sbeg;
        carry_len = l;
    }
    if (c == -1) {              /* str contains no alnum */
        s = e;
        while ((s = rb_enc_prev_char(sbeg, s, e, enc)) != 0) {
            enum neighbor_char neighbor;
            if ((l = rb_enc_precise_mbclen(s, e, enc)) <= 0) continue;
            neighbor = enc_succ_char(s, l, enc);
            if (neighbor == NEIGHBOR_FOUND)
                return str;
            if (rb_enc_precise_mbclen(s, s+l, enc) != l) {
                /* wrapped to \0...\0.  search next valid char. */
                enc_succ_char(s, l, enc);
            }
            if (!rb_enc_asciicompat(enc)) {
                MEMCPY(carry, s, char, l);
                carry_len = l;
            }
            carry_pos = s - sbeg;
        }
    }
    RESIZE_CAPA(str, RSTRING_LEN(str) + carry_len);
    s = RSTRING_PTR(str) + carry_pos;
    memmove(s + carry_len, s, RSTRING_LEN(str) - carry_pos);
    memmove(s, carry, carry_len);
    STR_SET_LEN(str, RSTRING_LEN(str) + carry_len);
    RSTRING_PTR(str)[RSTRING_LEN(str)] = '\0';
    rb_enc_str_coderange(str);
    return str;
}
            
succ! => str click to toggle source

Equivalent to String#succ, but modifies the receiver in place.

 
               static VALUE
rb_str_succ_bang(VALUE str)
{
    rb_str_shared_replace(str, rb_str_succ(str));

    return str;
}
            
sum(n=16) => integer click to toggle source

Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2n - 1. This is not a particularly good checksum.

 
               static VALUE
rb_str_sum(int argc, VALUE *argv, VALUE str)
{
    VALUE vbits;
    int bits;
    char *ptr, *p, *pend;
    long len;

    if (argc == 0) {
        bits = 16;
    }
    else {
        rb_scan_args(argc, argv, "01", &vbits);
        bits = NUM2INT(vbits);
    }
    ptr = p = RSTRING_PTR(str);
    len = RSTRING_LEN(str);
    pend = p + len;
    if (bits >= sizeof(long)*CHAR_BIT) {
        VALUE sum = INT2FIX(0);

        while (p < pend) {
            str_mod_check(str, ptr, len);
            sum = rb_funcall(sum, '+', 1, INT2FIX((unsigned char)*p));
            p++;
        }
        if (bits != 0) {
            VALUE mod;

            mod = rb_funcall(INT2FIX(1), rb_intern("<<"), 1, INT2FIX(bits));
            mod = rb_funcall(mod, '-', 1, INT2FIX(1));
            sum = rb_funcall(sum, '&', 1, mod);
        }
        return sum;
    }
    else {
       unsigned long sum = 0;

        while (p < pend) {
            str_mod_check(str, ptr, len);
            sum += (unsigned char)*p;
            p++;
        }
        if (bits != 0) {
           sum &= (((unsigned long)1)<<bits)-1;
        }
        return rb_int2inum(sum);
    }
}
            
swapcase => new_str click to toggle source

Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. Note: case conversion is effective only in ASCII region.

"Hello".swapcase          #=> "hELLO"
"cYbEr_PuNk11".swapcase   #=> "CyBeR_pUnK11"
 
               static VALUE
rb_str_swapcase(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_swapcase_bang(str);
    return str;
}
            
swapcase! => str or nil click to toggle source

Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. Note: case conversion is effective only in ASCII region.

 
               static VALUE
rb_str_swapcase_bang(VALUE str)
{
    rb_encoding *enc;
    char *s, *send;
    int modify = 0;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    rb_str_check_dummy_enc(enc);
    s = RSTRING_PTR(str); send = RSTRING_END(str);
    while (s < send) {
        unsigned int c = rb_enc_codepoint(s, send, enc);

        if (rb_enc_isupper(c, enc)) {
            /* assuming toupper returns codepoint with same size */
            rb_enc_mbcput(rb_enc_tolower(c, enc), s, enc);
            modify = 1;
        }
        else if (rb_enc_islower(c, enc)) {
            /* assuming tolower returns codepoint with same size */
            rb_enc_mbcput(rb_enc_toupper(c, enc), s, enc);
            modify = 1;
        }
        s += rb_enc_mbclen(s, send, enc);
    }

    if (modify) return str;
    return Qnil;
}
            
to_c() click to toggle source
 
               static VALUE
string_to_c(VALUE self)
{
    VALUE s, a, backref;

    backref = rb_backref_get();
    rb_match_busy(backref);

    s = f_gsub(self, underscores_pat, an_underscore);
    a = string_to_c_internal(s);

    rb_backref_set(backref);

    if (!NIL_P(RARRAY_PTR(a)[0]))
        return RARRAY_PTR(a)[0];
    return rb_complex_new1(INT2FIX(0));
}
            
to_f => float click to toggle source

Returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception.

"123.45e1".to_f        #=> 1234.5
"45.67 degrees".to_f   #=> 45.67
"thx1138".to_f         #=> 0.0
 
               static VALUE
rb_str_to_f(VALUE str)
{
    return DBL2NUM(rb_str_to_dbl(str, Qfalse));
}
            
to_i(base=10) => integer click to toggle source

Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception.

"12345".to_i             #=> 12345
"99 red balloons".to_i   #=> 99
"0a".to_i                #=> 0
"0a".to_i(16)            #=> 10
"hello".to_i             #=> 0
"1100101".to_i(2)        #=> 101
"1100101".to_i(8)        #=> 294977
"1100101".to_i(10)       #=> 1100101
"1100101".to_i(16)       #=> 17826049
 
               static VALUE
rb_str_to_i(int argc, VALUE *argv, VALUE str)
{
    int base;

    if (argc == 0) base = 10;
    else {
        VALUE b;

        rb_scan_args(argc, argv, "01", &b);
        base = NUM2INT(b);
    }
    if (base < 0) {
        rb_raise(rb_eArgError, "invalid radix %d", base);
    }
    return rb_str_to_inum(str, base, Qfalse);
}
            
to_r() click to toggle source
 
               static VALUE
string_to_r(VALUE self)
{
    VALUE s, a, backref;

    backref = rb_backref_get();
    rb_match_busy(backref);

    s = f_gsub(self, underscores_pat, an_underscore);
    a = string_to_r_internal(s);

    rb_backref_set(backref);

    if (!NIL_P(RARRAY_PTR(a)[0]))
        return RARRAY_PTR(a)[0];
    return rb_rational_new1(INT2FIX(0));
}
            
to_s => str click to toggle source
to_str => str

Returns the receiver.

 
               static VALUE
rb_str_to_s(VALUE str)
{
    if (rb_obj_class(str) != rb_cString) {
        return str_duplicate(rb_cString, str);
    }
    return str;
}
            
to_str => str click to toggle source

Returns the receiver.

 
               static VALUE
rb_str_to_s(VALUE str)
{
    if (rb_obj_class(str) != rb_cString) {
        return str_duplicate(rb_cString, str);
    }
    return str;
}
            
to_sym => symbol click to toggle source

Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name.

"Koala".intern         #=> :Koala
s = 'cat'.to_sym       #=> :cat
s == :cat              #=> true
s = '@cat'.to_sym      #=> :@cat
s == :@cat             #=> true

This can also be used to create symbols that cannot be represented using the :xxx notation.

'cat and dog'.to_sym   #=> :"cat and dog"
 
               VALUE
rb_str_intern(VALUE s)
{
    VALUE str = RB_GC_GUARD(s);
    ID id;

    id = rb_intern_str(str);
    return ID2SYM(id);
}
            
tr(from_str, to_str) => new_str click to toggle source

Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character. Both strings may use the c1–c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed.

"hello".tr('aeiou', '*')    #=> "h*ll*"
"hello".tr('^aeiou', '*')   #=> "*e**o"
"hello".tr('el', 'ip')      #=> "hippo"
"hello".tr('a-y', 'b-z')    #=> "ifmmp"
 
               static VALUE
rb_str_tr(VALUE str, VALUE src, VALUE repl)
{
    str = rb_str_dup(str);
    tr_trans(str, src, repl, 0);
    return str;
}
            
tr!(from_str, to_str) => str or nil click to toggle source

Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made.

 
               static VALUE
rb_str_tr_bang(VALUE str, VALUE src, VALUE repl)
{
    return tr_trans(str, src, repl, 0);
}
            
tr_s(from_str, to_str) => new_str click to toggle source

Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation.

"hello".tr_s('l', 'r')     #=> "hero"
"hello".tr_s('el', '*')    #=> "h*o"
"hello".tr_s('el', 'hx')   #=> "hhxo"
 
               static VALUE
rb_str_tr_s(VALUE str, VALUE src, VALUE repl)
{
    str = rb_str_dup(str);
    tr_trans(str, src, repl, 1);
    return str;
}
            
tr_s!(from_str, to_str) => str or nil click to toggle source

Performs String#tr_s processing on str in place, returning str, or nil if no changes were made.

 
               static VALUE
rb_str_tr_s_bang(VALUE str, VALUE src, VALUE repl)
{
    return tr_trans(str, src, repl, 1);
}
            
unpack(format) => anArray click to toggle source

Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (“*'') will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (“_'') to use the underlying platform's native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also Array#pack.

"abc \0\0abc \0\0".unpack('A6Z6')   #=> ["abc", "abc "]
"abc \0\0".unpack('a3a3')           #=> ["abc", " \000\000"]
"abc \0abc \0".unpack('Z*Z*')       #=> ["abc ", "abc "]
"aa".unpack('b8B8')                 #=> ["10000110", "01100001"]
"aaa".unpack('h2H2c')               #=> ["16", "61", 97]
"\xfe\xff\xfe\xff".unpack('sS')     #=> [-2, 65534]
"now=20is".unpack('M*')             #=> ["now is"]
"whole".unpack('xax2aX2aX1aX2a')    #=> ["h", "e", "l", "l", "o"]

This table summarizes the various formats and the Ruby classes returned by each.

Format | Returns | Function
-------+---------+-----------------------------------------
  A    | String  | arbitrary binary string with trailing
       |         | nulls and ASCII spaces removed
-------+---------+-----------------------------------------
  a    | String  | arbitrary binary string
-------+---------+-----------------------------------------
  B    | String  | extract bits from each character (msb first)
-------+---------+-----------------------------------------
  b    | String  | extract bits from each character (lsb first)
-------+---------+-----------------------------------------
  C    | Fixnum  | extract a byte (C char) as an unsigned integer
-------+---------+-----------------------------------------
  c    | Fixnum  | extract a byte (C char) as an integer
-------+---------+-----------------------------------------
  d,D  | Float   | treat sizeof(double) characters as
       |         | a native double
-------+---------+-----------------------------------------
  E    | Float   | treat sizeof(double) characters as
       |         | a double in little-endian byte order
-------+---------+-----------------------------------------
  e    | Float   | treat sizeof(float) characters as
       |         | a float in little-endian byte order
-------+---------+-----------------------------------------
  f,F  | Float   | treat sizeof(float) characters as
       |         | a native float
-------+---------+-----------------------------------------
  G    | Float   | treat sizeof(double) characters as
       |         | a double in network byte order
-------+---------+-----------------------------------------
  g    | Float   | treat sizeof(float) characters as a
       |         | float in network byte order
-------+---------+-----------------------------------------
  H    | String  | extract hex nibbles from each character
       |         | (most significant first)
-------+---------+-----------------------------------------
  h    | String  | extract hex nibbles from each character
       |         | (least significant first)
-------+---------+-----------------------------------------
  I    | Integer | treat sizeof(int) (modified by _)
       |         | successive characters as an unsigned
       |         | native integer
-------+---------+-----------------------------------------
  i    | Integer | treat sizeof(int) (modified by _)
       |         | successive characters as a signed
       |         | native integer
-------+---------+-----------------------------------------
  L    | Integer | treat four (modified by _) successive
       |         | characters as an unsigned native
       |         | long integer
-------+---------+-----------------------------------------
  l    | Integer | treat four (modified by _) successive
       |         | characters as a signed native
       |         | long integer
-------+---------+-----------------------------------------
  M    | String  | quoted-printable
-------+---------+-----------------------------------------
  m    | String  | base64-encoded (RFC 2045) (default)
       |         | base64-encoded (RFC 4648) if followed by 0
-------+---------+-----------------------------------------
  N    | Integer | treat four characters as an unsigned
       |         | long in network byte order
-------+---------+-----------------------------------------
  n    | Fixnum  | treat two characters as an unsigned
       |         | short in network byte order
-------+---------+-----------------------------------------
  P    | String  | treat sizeof(char *) characters as a
       |         | pointer, and  return \emph{len} characters
       |         | from the referenced location
-------+---------+-----------------------------------------
  p    | String  | treat sizeof(char *) characters as a
       |         | pointer to a  null-terminated string
-------+---------+-----------------------------------------
  Q    | Integer | treat 8 characters as an unsigned
       |         | quad word (64 bits)
-------+---------+-----------------------------------------
  q    | Integer | treat 8 characters as a signed
       |         | quad word (64 bits)
-------+---------+-----------------------------------------
  S    | Fixnum  | treat two (different if _ used)
       |         | successive characters as an unsigned
       |         | short in native byte order
-------+---------+-----------------------------------------
  s    | Fixnum  | Treat two (different if _ used)
       |         | successive characters as a signed short
       |         | in native byte order
-------+---------+-----------------------------------------
  U    | Integer | UTF-8 characters as unsigned integers
-------+---------+-----------------------------------------
  u    | String  | UU-encoded
-------+---------+-----------------------------------------
  V    | Fixnum  | treat four characters as an unsigned
       |         | long in little-endian byte order
-------+---------+-----------------------------------------
  v    | Fixnum  | treat two characters as an unsigned
       |         | short in little-endian byte order
-------+---------+-----------------------------------------
  w    | Integer | BER-compressed integer (see Array.pack)
-------+---------+-----------------------------------------
  X    | ---     | skip backward one character
-------+---------+-----------------------------------------
  x    | ---     | skip forward one character
-------+---------+-----------------------------------------
  Z    | String  | with trailing nulls removed
       |         | upto first null with *
-------+---------+-----------------------------------------
  @    | ---     | skip to the offset given by the
       |         | length argument
-------+---------+-----------------------------------------
 
               static VALUE
pack_unpack(VALUE str, VALUE fmt)
{
    static const char hexdigits[] = "0123456789abcdef";
    char *s, *send;
    char *p, *pend;
    VALUE ary;
    char type;
    long len;
    int tmp, star;
#ifdef NATINT_PACK
    int natint;                 /* native integer */
#endif
    int block_p = rb_block_given_p();
#define UNPACK_PUSH(item) do {\
        VALUE item_val = (item);\
        if (block_p) {\
            rb_yield(item_val);\
        }\
        else {\
            rb_ary_push(ary, item_val);\
        }\
    } while (0)

    StringValue(str);
    StringValue(fmt);
    s = RSTRING_PTR(str);
    send = s + RSTRING_LEN(str);
    p = RSTRING_PTR(fmt);
    pend = p + RSTRING_LEN(fmt);

    ary = block_p ? Qnil : rb_ary_new();
    while (p < pend) {
        type = *p++;
#ifdef NATINT_PACK
        natint = 0;
#endif

        if (ISSPACE(type)) continue;
        if (type == '#') {
            while ((p < pend) && (*p != '\n')) {
                p++;
            }
            continue;
        }
        star = 0;
        if (*p == '_' || *p == '!') {
            static const char natstr[] = "sSiIlL";

            if (strchr(natstr, type)) {
#ifdef NATINT_PACK
                natint = 1;
#endif
                p++;
            }
            else {
                rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
            }
        }
        if (p >= pend)
            len = 1;
        else if (*p == '*') {
            star = 1;
            len = send - s;
            p++;
        }
        else if (ISDIGIT(*p)) {
            errno = 0;
            len = STRTOUL(p, (char**)&p, 10);
            if (errno) {
                rb_raise(rb_eRangeError, "pack length too big");
            }
        }
        else {
            len = (type != '@');
        }

        switch (type) {
          case '%':
            rb_raise(rb_eArgError, "%% is not supported");
            break;

          case 'A':
            if (len > send - s) len = send - s;
            {
                long end = len;
                char *t = s + len - 1;

                while (t >= s) {
                    if (*t != ' ' && *t != '\0') break;
                    t--; len--;
                }
                UNPACK_PUSH(infected_str_new(s, len, str));
                s += end;
            }
            break;

          case 'Z':
            {
                char *t = s;

                if (len > send-s) len = send-s;
                while (t < s+len && *t) t++;
                UNPACK_PUSH(infected_str_new(s, t-s, str));
                if (t < send) t++;
                s = star ? t : s+len;
            }
            break;

          case 'a':
            if (len > send - s) len = send - s;
            UNPACK_PUSH(infected_str_new(s, len, str));
            s += len;
            break;

          case 'b':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 8)
                    len = (send - s) * 8;
                bits = 0;
                UNPACK_PUSH(bitstr = rb_str_new(0, len));
                t = RSTRING_PTR(bitstr);
                for (i=0; i<len; i++) {
                    if (i & 7) bits >>= 1;
                    else bits = *s++;
                    *t++ = (bits & 1) ? '1' : '0';
                }
            }
            break;

          case 'B':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 8)
                    len = (send - s) * 8;
                bits = 0;
                UNPACK_PUSH(bitstr = rb_str_new(0, len));
                t = RSTRING_PTR(bitstr);
                for (i=0; i<len; i++) {
                    if (i & 7) bits <<= 1;
                    else bits = *s++;
                    *t++ = (bits & 128) ? '1' : '0';
                }
            }
            break;

          case 'h':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 2)
                    len = (send - s) * 2;
                bits = 0;
                UNPACK_PUSH(bitstr = rb_str_new(0, len));
                t = RSTRING_PTR(bitstr);
                for (i=0; i<len; i++) {
                    if (i & 1)
                        bits >>= 4;
                    else
                        bits = *s++;
                    *t++ = hexdigits[bits & 15];
                }
            }
            break;

          case 'H':
            {
                VALUE bitstr;
                char *t;
                int bits;
                long i;

                if (p[-1] == '*' || len > (send - s) * 2)
                    len = (send - s) * 2;
                bits = 0;
                UNPACK_PUSH(bitstr = rb_str_new(0, len));
                t = RSTRING_PTR(bitstr);
                for (i=0; i<len; i++) {
                    if (i & 1)
                        bits <<= 4;
                    else
                        bits = *s++;
                    *t++ = hexdigits[(bits >> 4) & 15];
                }
            }
            break;

          case 'c':
            PACK_LENGTH_ADJUST(char,sizeof(char));
            while (len-- > 0) {
                int c = *s++;
                if (c > (char)127) c-=256;
                UNPACK_PUSH(INT2FIX(c));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'C':
            PACK_LENGTH_ADJUST(unsigned char,sizeof(unsigned char));
            while (len-- > 0) {
                unsigned char c = *s++;
                UNPACK_PUSH(INT2FIX(c));
            }
            PACK_ITEM_ADJUST();
            break;

          case 's':
            PACK_LENGTH_ADJUST(short,2);
            while (len-- > 0) {
                short tmp = 0;
                memcpy(OFF16(&tmp), s, NATINT_LEN(short,2));
                EXTEND16(tmp);
                s += NATINT_LEN(short,2);
                UNPACK_PUSH(INT2FIX(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'S':
            PACK_LENGTH_ADJUST(unsigned short,2);
            while (len-- > 0) {
                unsigned short tmp = 0;
                memcpy(OFF16(&tmp), s, NATINT_LEN(unsigned short,2));
                s += NATINT_LEN(unsigned short,2);
                UNPACK_PUSH(INT2FIX(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'i':
            PACK_LENGTH_ADJUST(int,sizeof(int));
            while (len-- > 0) {
                int tmp;
                memcpy(&tmp, s, sizeof(int));
                s += sizeof(int);
                UNPACK_PUSH(INT2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'I':
            PACK_LENGTH_ADJUST(unsigned int,sizeof(unsigned int));
            while (len-- > 0) {
                unsigned int tmp;
                memcpy(&tmp, s, sizeof(unsigned int));
                s += sizeof(unsigned int);
                UNPACK_PUSH(UINT2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'l':
            PACK_LENGTH_ADJUST(long,4);
            while (len-- > 0) {
                long tmp = 0;
                memcpy(OFF32(&tmp), s, NATINT_LEN(long,4));
                EXTEND32(tmp);
                s += NATINT_LEN(long,4);
                UNPACK_PUSH(LONG2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;
          case 'L':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(OFF32(&tmp), s, NATINT_LEN(unsigned long,4));
                s += NATINT_LEN(unsigned long,4);
                UNPACK_PUSH(ULONG2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'q':
            PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
            while (len-- > 0) {
                char *tmp = (char*)s;
                s += QUAD_SIZE;
                UNPACK_PUSH(rb_quad_unpack(tmp, 1));
            }
            PACK_ITEM_ADJUST();
            break;
          case 'Q':
            PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
            while (len-- > 0) {
                char *tmp = (char*)s;
                s += QUAD_SIZE;
                UNPACK_PUSH(rb_quad_unpack(tmp, 0));
            }
            break;

          case 'n':
            PACK_LENGTH_ADJUST(unsigned short,2);
            while (len-- > 0) {
                unsigned short tmp = 0;
                memcpy(OFF16B(&tmp), s, NATINT_LEN(unsigned short,2));
                s += NATINT_LEN(unsigned short,2);
                UNPACK_PUSH(UINT2NUM(ntohs(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'N':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(OFF32B(&tmp), s, NATINT_LEN(unsigned long,4));
                s += NATINT_LEN(unsigned long,4);
                UNPACK_PUSH(ULONG2NUM(ntohl(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'v':
            PACK_LENGTH_ADJUST(unsigned short,2);
            while (len-- > 0) {
                unsigned short tmp = 0;
                memcpy(&tmp, s, NATINT_LEN(unsigned short,2));
                s += NATINT_LEN(unsigned short,2);
                UNPACK_PUSH(UINT2NUM(vtohs(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'V':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(&tmp, s, NATINT_LEN(long,4));
                s += NATINT_LEN(long,4);
                UNPACK_PUSH(ULONG2NUM(vtohl(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'f':
          case 'F':
            PACK_LENGTH_ADJUST(float,sizeof(float));
            while (len-- > 0) {
                float tmp;
                memcpy(&tmp, s, sizeof(float));
                s += sizeof(float);
                UNPACK_PUSH(DBL2NUM((double)tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'e':
            PACK_LENGTH_ADJUST(float,sizeof(float));
            while (len-- > 0) {
                float tmp;
                FLOAT_CONVWITH(ftmp);

                memcpy(&tmp, s, sizeof(float));
                s += sizeof(float);
                tmp = VTOHF(tmp,ftmp);
                UNPACK_PUSH(DBL2NUM((double)tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'E':
            PACK_LENGTH_ADJUST(double,sizeof(double));
            while (len-- > 0) {
                double tmp;
                DOUBLE_CONVWITH(dtmp);

                memcpy(&tmp, s, sizeof(double));
                s += sizeof(double);
                tmp = VTOHD(tmp,dtmp);
                UNPACK_PUSH(DBL2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'D':
          case 'd':
            PACK_LENGTH_ADJUST(double,sizeof(double));
            while (len-- > 0) {
                double tmp;
                memcpy(&tmp, s, sizeof(double));
                s += sizeof(double);
                UNPACK_PUSH(DBL2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'g':
            PACK_LENGTH_ADJUST(float,sizeof(float));
            while (len-- > 0) {
                float tmp;
                FLOAT_CONVWITH(ftmp;)

                memcpy(&tmp, s, sizeof(float));
                s += sizeof(float);
                tmp = NTOHF(tmp,ftmp);
                UNPACK_PUSH(DBL2NUM((double)tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'G':
            PACK_LENGTH_ADJUST(double,sizeof(double));
            while (len-- > 0) {
                double tmp;
                DOUBLE_CONVWITH(dtmp);

                memcpy(&tmp, s, sizeof(double));
                s += sizeof(double);
                tmp = NTOHD(tmp,dtmp);
                UNPACK_PUSH(DBL2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'U':
            if (len > send - s) len = send - s;
            while (len > 0 && s < send) {
                long alen = send - s;
                unsigned long l;

                l = utf8_to_uv(s, &alen);
                s += alen; len--;
                UNPACK_PUSH(ULONG2NUM(l));
            }
            break;

          case 'u':
            {
                VALUE buf = infected_str_new(0, (send - s)*3/4, str);
                char *ptr = RSTRING_PTR(buf);
                long total = 0;

                while (s < send && *s > ' ' && *s < 'a') {
                    long a,b,c,d;
                    char hunk[4];

                    hunk[3] = '\0';
                    len = (*s++ - ' ') & 077;
                    total += len;
                    if (total > RSTRING_LEN(buf)) {
                        len -= total - RSTRING_LEN(buf);
                        total = RSTRING_LEN(buf);
                    }

                    while (len > 0) {
                        long mlen = len > 3 ? 3 : len;

                        if (s < send && *s >= ' ')
                            a = (*s++ - ' ') & 077;
                        else
                            a = 0;
                        if (s < send && *s >= ' ')
                            b = (*s++ - ' ') & 077;
                        else
                            b = 0;
                        if (s < send && *s >= ' ')
                            c = (*s++ - ' ') & 077;
                        else
                            c = 0;
                        if (s < send && *s >= ' ')
                            d = (*s++ - ' ') & 077;
                        else
                            d = 0;
                        hunk[0] = a << 2 | b >> 4;
                        hunk[1] = b << 4 | c >> 2;
                        hunk[2] = c << 6 | d;
                        memcpy(ptr, hunk, mlen);
                        ptr += mlen;
                        len -= mlen;
                    }
                    if (*s == '\r') s++;
                    if (*s == '\n') s++;
                    else if (s < send && (s+1 == send || s[1] == '\n'))
                        s += 2;      /* possible checksum byte */
                }

                rb_str_set_len(buf, total);
                UNPACK_PUSH(buf);
            }
            break;

          case 'm':
            {
                VALUE buf = infected_str_new(0, (send - s)*3/4, str);
                char *ptr = RSTRING_PTR(buf);
                int a = -1,b = -1,c = 0,d = 0;
                static signed char b64_xtable[256];

                if (b64_xtable['/'] <= 0) {
                    int i;

                    for (i = 0; i < 256; i++) {
                        b64_xtable[i] = -1;
                    }
                    for (i = 0; i < 64; i++) {
                        b64_xtable[(unsigned char)b64_table[i]] = i;
                    }
                }
                if (len == 0) {
                    while (s < send) {
                        a = b = c = d = -1;
                        a = b64_xtable[(unsigned char)*s++];
                        if (s >= send || a == -1) rb_raise(rb_eArgError, "invalid base64");
                        b = b64_xtable[(unsigned char)*s++];
                        if (s >= send || b == -1) rb_raise(rb_eArgError, "invalid base64");
                        if (*s == '=') {
                            if (s + 2 == send && *(s + 1) == '=') break;
                            rb_raise(rb_eArgError, "invalid base64");
                        }
                        c = b64_xtable[(unsigned char)*s++];
                        if (s >= send || c == -1) rb_raise(rb_eArgError, "invalid base64");
                        if (s + 1 == send && *s == '=') break;
                        d = b64_xtable[(unsigned char)*s++];
                        if (d == -1) rb_raise(rb_eArgError, "invalid base64");
                        *ptr++ = a << 2 | b >> 4;
                        *ptr++ = b << 4 | c >> 2;
                        *ptr++ = c << 6 | d;
                    }
                    if (c == -1) {
                        *ptr++ = a << 2 | b >> 4;
                        if (b & 0xf) rb_raise(rb_eArgError, "invalid base64");
                    }
                    else if (d == -1) {
                        *ptr++ = a << 2 | b >> 4;
                        *ptr++ = b << 4 | c >> 2;
                        if (c & 0x3) rb_raise(rb_eArgError, "invalid base64");
                    }
                }
                else {
                    while (s < send) {
                        a = b = c = d = -1;
                        while ((a = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
                        if (s >= send) break;
                        s++;
                        while ((b = b64_xtable[(unsigned char)*s]) == -1 && s < send) {s++;}
                        if (s >= send) break;
                        s++;
                        while ((c = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
                        if (*s == '=' || s >= send) break;
                        s++;
                        while ((d = b64_xtable[(unsigned char)*s]) == -1 && s < send) {if (*s == '=') break; s++;}
                        if (*s == '=' || s >= send) break;
                        s++;
                        *ptr++ = a << 2 | b >> 4;
                        *ptr++ = b << 4 | c >> 2;
                        *ptr++ = c << 6 | d;
                    }
                    if (a != -1 && b != -1) {
                        if (c == -1 && *s == '=')
                            *ptr++ = a << 2 | b >> 4;
                        else if (c != -1 && *s == '=') {
                            *ptr++ = a << 2 | b >> 4;
                            *ptr++ = b << 4 | c >> 2;
                        }
                    }
                }
                rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
                UNPACK_PUSH(buf);
            }
            break;

          case 'M':
            {
                VALUE buf = infected_str_new(0, send - s, str);
                char *ptr = RSTRING_PTR(buf);
                int c1, c2;

                while (s < send) {
                    if (*s == '=') {
                        if (++s == send) break;
                       if (s+1 < send && *s == '\r' && *(s+1) == '\n')
                         s++;
                        if (*s != '\n') {
                            if ((c1 = hex2num(*s)) == -1) break;
                            if (++s == send) break;
                            if ((c2 = hex2num(*s)) == -1) break;
                            *ptr++ = c1 << 4 | c2;
                        }
                    }
                    else {
                        *ptr++ = *s;
                    }
                    s++;
                }
                rb_str_set_len(buf, ptr - RSTRING_PTR(buf));
                ENCODING_CODERANGE_SET(buf, rb_usascii_encindex(), ENC_CODERANGE_7BIT);
                UNPACK_PUSH(buf);
            }
            break;

          case '@':
            if (len > RSTRING_LEN(str))
                rb_raise(rb_eArgError, "@ outside of string");
            s = RSTRING_PTR(str) + len;
            break;

          case 'X':
            if (len > s - RSTRING_PTR(str))
                rb_raise(rb_eArgError, "X outside of string");
            s -= len;
            break;

          case 'x':
            if (len > send - s)
                rb_raise(rb_eArgError, "x outside of string");
            s += len;
            break;

          case 'P':
            if (sizeof(char *) <= send - s) {
                VALUE tmp = Qnil;
                char *t;

                memcpy(&t, s, sizeof(char *));
                s += sizeof(char *);

                if (t) {
                    VALUE a, *p, *pend;

                    if (!(a = rb_str_associated(str))) {
                        rb_raise(rb_eArgError, "no associated pointer");
                    }
                    p = RARRAY_PTR(a);
                    pend = p + RARRAY_LEN(a);
                    while (p < pend) {
                        if (TYPE(*p) == T_STRING && RSTRING_PTR(*p) == t) {
                            if (len < RSTRING_LEN(*p)) {
                                tmp = rb_tainted_str_new(t, len);
                                rb_str_associate(tmp, a);
                            }
                            else {
                                tmp = *p;
                            }
                            break;
                        }
                        p++;
                    }
                    if (p == pend) {
                        rb_raise(rb_eArgError, "non associated pointer");
                    }
                }
                UNPACK_PUSH(tmp);
            }
            break;

          case 'p':
            if (len > (send - s) / sizeof(char *))
                len = (send - s) / sizeof(char *);
            while (len-- > 0) {
                if (send - s < sizeof(char *))
                    break;
                else {
                    VALUE tmp = Qnil;
                    char *t;

                    memcpy(&t, s, sizeof(char *));
                    s += sizeof(char *);

                    if (t) {
                        VALUE a, *p, *pend;

                        if (!(a = rb_str_associated(str))) {
                            rb_raise(rb_eArgError, "no associated pointer");
                        }
                        p = RARRAY_PTR(a);
                        pend = p + RARRAY_LEN(a);
                        while (p < pend) {
                            if (TYPE(*p) == T_STRING && RSTRING_PTR(*p) == t) {
                                tmp = *p;
                                break;
                            }
                            p++;
                        }
                        if (p == pend) {
                            rb_raise(rb_eArgError, "non associated pointer");
                        }
                    }
                    UNPACK_PUSH(tmp);
                }
            }
            break;

          case 'w':
            {
                unsigned long ul = 0;
                unsigned long ulmask = 0xfeUL << ((sizeof(unsigned long) - 1) * 8);

                while (len > 0 && s < send) {
                    ul <<= 7;
                    ul |= (*s & 0x7f);
                    if (!(*s++ & 0x80)) {
                        UNPACK_PUSH(ULONG2NUM(ul));
                        len--;
                        ul = 0;
                    }
                    else if (ul & ulmask) {
                        VALUE big = rb_uint2big(ul);
                        VALUE big128 = rb_uint2big(128);
                        while (s < send) {
                            big = rb_big_mul(big, big128);
                            big = rb_big_plus(big, rb_uint2big(*s & 0x7f));
                            if (!(*s++ & 0x80)) {
                                UNPACK_PUSH(big);
                                len--;
                                ul = 0;
                                break;
                            }
                        }
                    }
                }
            }
            break;

          default:
            break;
        }
    }

    return ary;
}
            
upcase => new_str click to toggle source

Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive—only characters “a'' to “z'' are affected. Note: case replacement is effective only in ASCII region.

"hEllO".upcase   #=> "HELLO"
 
               static VALUE
rb_str_upcase(VALUE str)
{
    str = rb_str_dup(str);
    rb_str_upcase_bang(str);
    return str;
}
            
upcase! => str or nil click to toggle source

Upcases the contents of str, returning nil if no changes were made. Note: case replacement is effective only in ASCII region.

 
               static VALUE
rb_str_upcase_bang(VALUE str)
{
    rb_encoding *enc;
    char *s, *send;
    int modify = 0;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    rb_str_check_dummy_enc(enc);
    s = RSTRING_PTR(str); send = RSTRING_END(str);
    if (single_byte_optimizable(str)) {
        while (s < send) {
            unsigned int c = *(unsigned char*)s;

            if (rb_enc_isascii(c, enc) && 'a' <= c && c <= 'z') {
                *s = 'A' + (c - 'a');
                modify = 1;
            }
            s++;
        }
    }
    else {
        int ascompat = rb_enc_asciicompat(enc);

        while (s < send) {
            unsigned int c;

            if (ascompat && (c = *(unsigned char*)s) < 0x80) {
                if (rb_enc_isascii(c, enc) && 'a' <= c && c <= 'z') {
                    *s = 'A' + (c - 'a');
                    modify = 1;
                }
                s++;
            }
            else {
                c = rb_enc_codepoint(s, send, enc);
                if (rb_enc_islower(c, enc)) {
                    /* assuming toupper returns codepoint with same size */
                    rb_enc_mbcput(rb_enc_toupper(c, enc), s, enc);
                    modify = 1;
                }
                s += rb_enc_codelen(c, enc);
            }
        }
    }

    if (modify) return str;
    return Qnil;
}
            
upto(other_str, exclusive=false) {|s| block } => str click to toggle source

Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ method is used to generate each value. If optional second argument exclusive is omitted or is false, the last value will be included; otherwise it will be excluded.

"a8".upto("b6") {|s| print s, ' ' }
for s in "a8".."b6"
  print s, ' '
end

produces:

a8 a9 b0 b1 b2 b3 b4 b5 b6
a8 a9 b0 b1 b2 b3 b4 b5 b6
 
               static VALUE
rb_str_upto(int argc, VALUE *argv, VALUE beg)
{
    VALUE end, exclusive;
    VALUE current, after_end;
    ID succ;
    int n, excl;
    rb_encoding *enc;

    rb_scan_args(argc, argv, "11", &end, &exclusive);
    RETURN_ENUMERATOR(beg, argc, argv);
    excl = RTEST(exclusive);
    CONST_ID(succ, "succ");
    StringValue(end);
    enc = rb_enc_check(beg, end);
    if (RSTRING_LEN(beg) == 1 && RSTRING_LEN(end) == 1 &&
        is_ascii_string(beg) && is_ascii_string(end)) {
        char c = RSTRING_PTR(beg)[0];
        char e = RSTRING_PTR(end)[0];

        if (c > e || (excl && c == e)) return beg;
        for (;;) {
            rb_yield(rb_enc_str_new(&c, 1, enc));
            if (!excl && c == e) break;
            c++;
            if (excl && c == e) break;
        }
        return beg;
    }
    n = rb_str_cmp(beg, end);
    if (n > 0 || (excl && n == 0)) return beg;
        
    after_end = rb_funcall(end, succ, 0, 0);
    current = beg;
    while (!rb_str_equal(current, after_end)) {
        rb_yield(current);
        if (!excl && rb_str_equal(current, end)) break;
        current = rb_funcall(current, succ, 0, 0);
        StringValue(current);
        if (excl && rb_str_equal(current, end)) break;
        if (RSTRING_LEN(current) > RSTRING_LEN(end) || RSTRING_LEN(current) == 0)
            break;
    }

    return beg;
}
            
valid_encoding? => true or false click to toggle source

Returns true for a string which encoded correctly.

"\xc2\xa1".force_encoding("UTF-8").valid_encoding? => true
"\xc2".force_encoding("UTF-8").valid_encoding? => false
"\x80".force_encoding("UTF-8").valid_encoding? => false
 
               static VALUE
rb_str_valid_encoding_p(VALUE str)
{
    int cr = rb_enc_str_coderange(str);

    return cr == ENC_CODERANGE_BROKEN ? Qfalse : Qtrue;
}