In Files

  • pack.c
  • string.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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE orig;

    if (rb_scan_args(argc, argv, "01", &orig) == 1)
        rb_str_replace(str, orig);
    return 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.id ]   #=> "ID   : 200e14d6"
 
               static VALUE
rb_str_format_m(str, arg)
    VALUE str, 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(str, times)
    VALUE str;
    VALUE times;
{
    VALUE str2;
    long i, len;

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

    str2 = rb_str_new5(str,0, len *= RSTRING(str)->len);
    for (i = 0; i < len; i += RSTRING(str)->len) {
        memcpy(RSTRING(str2)->ptr + i,
               RSTRING(str)->ptr, RSTRING(str)->len);
    }
    RSTRING(str2)->ptr[RSTRING(str2)->len] = '\0';

    OBJ_INFECT(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(str1, str2)
    VALUE str1, str2;
{
    VALUE str3;

    StringValue(str2);
    str3 = rb_str_new(0, RSTRING(str1)->len+RSTRING(str2)->len);
    memcpy(RSTRING(str3)->ptr, RSTRING(str1)->ptr, RSTRING(str1)->len);
    memcpy(RSTRING(str3)->ptr + RSTRING(str1)->len,
           RSTRING(str2)->ptr, RSTRING(str2)->len);
    RSTRING(str3)->ptr[RSTRING(str3)->len] = '\0';

    if (OBJ_TAINTED(str1) || OBJ_TAINTED(str2))
        OBJ_TAINT(str3);
    return str3;
}
            
str << fixnum => str click to toggle source
str << obj => str

Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.

a = "hello "
a << "world"   #=> "hello world"
a.concat(33)   #=> "hello world!"
 
               VALUE
rb_str_concat(str1, str2)
    VALUE str1, str2;
{
    if (FIXNUM_P(str2)) {
        int i = FIX2INT(str2);
        if (0 <= i && i <= 0xff) { /* byte */
            char c = i;
            return rb_str_cat(str1, &c, 1);
        }
    }
    str1 = rb_str_append(str1, str2);

    return str1;
}
            
str <=> other_str => -1, 0, +1 click to toggle source

Comparison—Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater 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. If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. 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(str1, str2)
    VALUE str1, 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.

 
               static VALUE
rb_str_equal(str1, str2)
    VALUE str1, str2;
{
    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 (RSTRING(str1)->len == RSTRING(str2)->len &&
        rb_str_cmp(str1, str2) == 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      #=> false
 
               static VALUE
rb_str_match(x, y)
    VALUE x, 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] => fixnum 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 the code of the 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]                   #=> 101
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(argc, argv, str)
    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] = fixnum click to toggle source
str[fixnum] = new_str
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(argc, argv, str)
    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]);
}
            
capitalize => new_str click to toggle source

Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.

"hello".capitalize    #=> "Hello"
"HELLO".capitalize    #=> "Hello"
"123ABC".capitalize   #=> "123abc"
 
               static VALUE
rb_str_capitalize(str)
    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.

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

    rb_str_modify(str);
    if (RSTRING(str)->len == 0 || !RSTRING(str)->ptr) return Qnil;
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    if (ISLOWER(*s)) {
        *s = toupper(*s);
        modify = 1;
    }
    while (++s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISUPPER(*s)) {
            *s = tolower(*s);
            modify = 1;
        }
    }
    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(str1, str2)
    VALUE str1, str2;
{
    long len;
    int retval;

    StringValue(str2);
    len = lesser(RSTRING(str1)->len, RSTRING(str2)->len);
    retval = rb_memcicmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr, len);
    if (retval == 0) {
        if (RSTRING(str1)->len == RSTRING(str2)->len) return INT2FIX(0);
        if (RSTRING(str1)->len > RSTRING(str2)->len) return INT2FIX(1);
        return INT2FIX(-1);
    }
    if (retval == 0) return INT2FIX(0);
    if (retval > 0) 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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return rb_str_justify(argc, argv, str, 'c');
}
            
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(argc, argv, str)
    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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE rs;
    int newline;
    char *p;
    long len, rslen;

    if (rb_scan_args(argc, argv, "01", &rs) == 0) {
        len = RSTRING(str)->len;
        if (len == 0) return Qnil;
        p = RSTRING(str)->ptr;
        rs = rb_rs;
        if (rs == rb_default_rs) {
          smart_chomp:
            rb_str_modify(str);
            if (RSTRING(str)->ptr[len-1] == '\n') {
                RSTRING(str)->len--;
                if (RSTRING(str)->len > 0 &&
                    RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
                    RSTRING(str)->len--;
                }
            }
            else if (RSTRING(str)->ptr[len-1] == '\r') {
                RSTRING(str)->len--;
            }
            else {
                return Qnil;
            }
            RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
            return str;
        }
    }
    if (NIL_P(rs)) return Qnil;
    StringValue(rs);
    len = RSTRING(str)->len;
    if (len == 0) return Qnil;
    p = RSTRING(str)->ptr;
    rslen = RSTRING(rs)->len;
    if (rslen == 0) {
        while (len>0 && p[len-1] == '\n') {
            len--;
            if (len>0 && p[len-1] == '\r')
                len--;
        }
        if (len < RSTRING(str)->len) {
            rb_str_modify(str);
            RSTRING(str)->len = len;
            RSTRING(str)->ptr[len] = '\0';
            return str;
        }
        return Qnil;
    }
    if (rslen > len) return Qnil;
    newline = RSTRING(rs)->ptr[rslen-1];
    if (rslen == 1 && newline == '\n')
        goto smart_chomp;

    if (p[len-1] == newline &&
        (rslen <= 1 ||
         rb_memcmp(RSTRING(rs)->ptr, p+len-rslen, rslen) == 0)) {
        rb_str_modify(str);
        RSTRING(str)->len -= rslen;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\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(str)
    VALUE str;
{
    str = rb_str_dup(str);
    rb_str_chop_bang(str);
    return str;
}
            
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(str)
    VALUE str;
{
    if (RSTRING(str)->len > 0) {
        rb_str_modify(str);
        RSTRING(str)->len--;
        if (RSTRING(str)->ptr[RSTRING(str)->len] == '\n') {
            if (RSTRING(str)->len > 0 &&
                RSTRING(str)->ptr[RSTRING(str)->len-1] == '\r') {
                RSTRING(str)->len--;
            }
        }
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        return str;
    }
    return Qnil;
}
            
concat(fixnum) => str click to toggle source
concat(obj) => str

Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation.

a = "hello "
a << "world"   #=> "hello world"
a.concat(33)   #=> "hello world!"
 
               VALUE
rb_str_concat(str1, str2)
    VALUE str1, str2;
{
    if (FIXNUM_P(str2)) {
        int i = FIX2INT(str2);
        if (0 <= i && i <= 0xff) { /* byte */
            char c = i;
            return rb_str_cat(str1, &c, 1);
        }
    }
    str1 = rb_str_append(str1, str2);

    return str1;
}
            
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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    char table[256];
    char *s, *send;
    int init = 1;
    int i;

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

        StringValue(s);
        tr_setup_table(s, table, init);
        init = 0;
    }

    s = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return INT2FIX(0);
    send = s + RSTRING(str)->len;
    i = 0;
    while (s < send) {
        if (table[*s++ & 0xff]) {
            i++;
        }
    }
    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(str, salt)
    VALUE str, salt;
{
    extern char *crypt();
    VALUE result;
    char *s;

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

    if (RSTRING(str)->ptr) s = RSTRING(str)->ptr;
    else s = "";
    result = rb_str_new2(crypt(s, RSTRING(salt)->ptr));
    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(argc, argv, str)
    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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    char *s, *send, *t;
    char squeez[256];
    int modify = 0;
    int init = 1;
    int i;

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

        StringValue(s);
        tr_setup_table(s, squeez, init);
        init = 0;
    }

    rb_str_modify(str);
    s = t = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    send = s + RSTRING(str)->len;
    while (s < send) {
        if (squeez[*s & 0xff])
            modify = 1;
        else
            *t++ = *s;
        s++;
    }
    *t = '\0';
    RSTRING(str)->len = t - RSTRING(str)->ptr;

    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.

"hEllO".downcase   #=> "hello"
 
               static VALUE
rb_str_downcase(str)
    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.

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

    rb_str_modify(str);
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    while (s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISUPPER(*s)) {
            *s = tolower(*s);
            modify = 1;
        }
        s++;
    }

    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(str)
    VALUE str;
{
    long len;
    char *p, *pend;
    char *q, *qend;
    VALUE result;

    len = 2;                    /* "" */
    p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
    while (p < pend) {
        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 {
                len += 4;             /* \nnn */
            }
            break;
        }
    }

    result = rb_str_new5(str, 0, len);
    p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
    q = RSTRING(result)->ptr; qend = q + len;

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

        if (c == '"' || c == '\\') {
            *q++ = '\\';
            *q++ = c;
        }
        else if (c == '#') {
            if (IS_EVSTR(p, pend)) *q++ = '\\';
            *q++ = '#';
        }
        else if (ISPRINT(c)) {
            *q++ = c;
        }
        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 {
            *q++ = '\\';
            sprintf(q, "%03o", c&0xff);
            q += 3;
        }
    }
    *q++ = '"';

    OBJ_INFECT(result, str);
    return result;
}
            
each(separator=$/) {|substr| block } => str click to toggle source
each_line(separator=$/) {|substr| block } => str

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 on \n characters, except that multiple successive newlines are appended together.

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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE rs;
    int newline;
    char *p = RSTRING(str)->ptr, *pend = p + RSTRING(str)->len, *s;
    char *ptr = p;
    long len = RSTRING(str)->len, rslen;
    VALUE line;

    if (rb_scan_args(argc, argv, "01", &rs) == 0) {
        rs = rb_rs;
    }

    if (NIL_P(rs)) {
        rb_yield(str);
        return str;
    }
    StringValue(rs);
    rslen = RSTRING(rs)->len;
    if (rslen == 0) {
        newline = '\n';
    }
    else {
        newline = RSTRING(rs)->ptr[rslen-1];
    }

    for (s = p, p += rslen; p < pend; p++) {
        if (rslen == 0 && *p == '\n') {
            if (*++p != '\n') continue;
            while (*p == '\n') p++;
        }
        if (RSTRING(str)->ptr < p && p[-1] == newline &&
            (rslen <= 1 ||
             rb_memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) {
            line = rb_str_new5(str, s, p - s);
            OBJ_INFECT(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p;
        }
    }

    if (s != pend) {
        if (p > pend) p = pend;
        line = rb_str_new5(str, s, p - s);
        OBJ_INFECT(line, str);
        rb_yield(line);
    }

    return str;
}
            
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(str)
    VALUE str;
{
    long i;

    for (i=0; i<RSTRING(str)->len; i++) {
        rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff));
    }
    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 on \n characters, except that multiple successive newlines are appended together.

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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE rs;
    int newline;
    char *p = RSTRING(str)->ptr, *pend = p + RSTRING(str)->len, *s;
    char *ptr = p;
    long len = RSTRING(str)->len, rslen;
    VALUE line;

    if (rb_scan_args(argc, argv, "01", &rs) == 0) {
        rs = rb_rs;
    }

    if (NIL_P(rs)) {
        rb_yield(str);
        return str;
    }
    StringValue(rs);
    rslen = RSTRING(rs)->len;
    if (rslen == 0) {
        newline = '\n';
    }
    else {
        newline = RSTRING(rs)->ptr[rslen-1];
    }

    for (s = p, p += rslen; p < pend; p++) {
        if (rslen == 0 && *p == '\n') {
            if (*++p != '\n') continue;
            while (*p == '\n') p++;
        }
        if (RSTRING(str)->ptr < p && p[-1] == newline &&
            (rslen <= 1 ||
             rb_memcmp(RSTRING(rs)->ptr, p-rslen, rslen) == 0)) {
            line = rb_str_new5(str, s, p - s);
            OBJ_INFECT(line, str);
            rb_yield(line);
            str_mod_check(str, ptr, len);
            s = p;
        }
    }

    if (s != pend) {
        if (p > pend) p = pend;
        line = rb_str_new5(str, s, p - s);
        OBJ_INFECT(line, str);
        rb_yield(line);
    }

    return str;
}
            
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(str)
    VALUE str;
{
    if (RSTRING(str)->len == 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(str1, str2)
    VALUE str1, str2;
{
    if (TYPE(str2) != T_STRING || RSTRING(str1)->len != RSTRING(str2)->len)
        return Qfalse;

    if (memcmp(RSTRING(str1)->ptr, RSTRING(str2)->ptr,
               lesser(RSTRING(str1)->len, RSTRING(str2)->len)) == 0)
        return Qtrue;

    return Qfalse;
}
            
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, 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].to_s + ' '}   #=> "104 101 108 108 111 "
 
               static VALUE
rb_str_gsub(argc, argv, str)
    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(argc, argv, str)
    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(str)
    VALUE str;
{
    int key = rb_str_hash(str);
    return INT2FIX(key);
}
            
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(str)
    VALUE str;
{
    return rb_str_to_inum(str, 16, Qfalse);
}
            
include? other_str => true or false click to toggle source
include? fixnum => true or false

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(str, arg)
    VALUE str, arg;
{
    long i;

    if (FIXNUM_P(arg)) {
        if (memchr(RSTRING(str)->ptr, FIX2INT(arg), RSTRING(str)->len))
            return Qtrue;
        return Qfalse;
    }

    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(fixnum [, offset]) => fixnum or nil
index(regexp [, offset]) => fixnum or nil

Returns the index of the first occurrence of the given substring, character (fixnum), 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(101)             #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4
 
               static VALUE
rb_str_index_m(argc, argv, str)
    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 += RSTRING(str)->len;
        if (pos < 0) {
            if (TYPE(sub) == T_REGEXP) {
                rb_backref_set(Qnil);
            }
            return Qnil;
        }
    }

    switch (TYPE(sub)) {
      case T_REGEXP:
        pos = rb_reg_adjust_startpos(sub, str, pos, 0);
        pos = rb_reg_search(sub, str, pos, 0);
        break;

      case T_FIXNUM:
      {
          int c = FIX2INT(sub);
          long len = RSTRING(str)->len;
          unsigned char *p = (unsigned char*)RSTRING(str)->ptr;

          for (;pos<len;pos++) {
              if (p[pos] == c) return LONG2NUM(pos);
          }
          return Qnil;
      }

      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);
        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"
 
               static VALUE
rb_str_replace(str, str2)
    VALUE str, str2;
{
    if (str == str2) return str;

    StringValue(str2);
    if (FL_TEST(str2, ELTS_SHARED)) {
        if (str_independent(str)) {
            free(RSTRING(str)->ptr);
        }
        RSTRING(str)->len = RSTRING(str2)->len;
        RSTRING(str)->ptr = RSTRING(str2)->ptr;
        FL_SET(str, ELTS_SHARED);
        FL_UNSET(str, STR_ASSOC);
        RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
    }
    else {
        if (str_independent(str)) {
            rb_str_resize(str, RSTRING(str2)->len);
            memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len);
            if (!RSTRING(str)->ptr) {
                make_null_str(str);
            }
        }
        else {
            RSTRING(str)->ptr = RSTRING(str2)->ptr;
            RSTRING(str)->len = RSTRING(str2)->len;
            str_make_independent(str);
        }
        if (FL_TEST(str2, STR_ASSOC)) {
            FL_SET(str, STR_ASSOC);
            RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
        }
    }

    OBJ_INFECT(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(str, idx, str2)
    VALUE str, idx, str2;
{
    long pos = NUM2LONG(idx);

    if (pos == -1) {
        pos = RSTRING(str)->len;
    }
    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, with special characters escaped.

str = "hello"
str[3] = 8
str.inspect       #=> "hel\010o"
 
               VALUE
rb_str_inspect(str)
    VALUE str;
{
    char *p, *pend;
    VALUE result = rb_str_buf_new2("\"");
    char s[5];

    p = RSTRING(str)->ptr; pend = p + RSTRING(str)->len;
    while (p < pend) {
        char c = *p++;
        if (ismbchar(c) && p < pend) {
            int len = mbclen(c);
            rb_str_buf_cat(result, p - 1, len);
            p += len - 1;
        }
        else if (c == '"'|| c == '\\' || (c == '#' && IS_EVSTR(p, pend))) {
            s[0] = '\\'; s[1] = c;
            rb_str_buf_cat(result, s, 2);
        }
        else if (ISPRINT(c)) {
            s[0] = c;
            rb_str_buf_cat(result, s, 1);
        }
        else if (c == '\n') {
            s[0] = '\\'; s[1] = 'n';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\r') {
            s[0] = '\\'; s[1] = 'r';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\t') {
            s[0] = '\\'; s[1] = 't';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\f') {
            s[0] = '\\'; s[1] = 'f';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\013') {
            s[0] = '\\'; s[1] = 'v';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\010') {
            s[0] = '\\'; s[1] = 'b';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == '\007') {
            s[0] = '\\'; s[1] = 'a';
            rb_str_buf_cat(result, s, 2);
        }
        else if (c == 033) {
            s[0] = '\\'; s[1] = 'e';
            rb_str_buf_cat(result, s, 2);
        }
        else {
            sprintf(s, "\\%03o", c & 0377);
            rb_str_buf_cat2(result, s);
        }
    }
    rb_str_buf_cat2(result, "\"");

    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(s)
    VALUE s;
{
    volatile VALUE str = s;
    ID id;

    if (!RSTRING(str)->ptr || RSTRING(str)->len == 0) {
        rb_raise(rb_eArgError, "interning empty string");
    }
    if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len)
        rb_raise(rb_eArgError, "symbol string may not contain `\\0'");
    if (OBJ_TAINTED(str) && rb_safe_level() >= 1 && !rb_sym_interned_p(str)) {
        rb_raise(rb_eSecurityError, "Insecure: can't intern tainted string");
    }
    id = rb_intern(RSTRING(str)->ptr);
    return ID2SYM(id);
}
            
length => integer click to toggle source

Returns the length of str.

 
               static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}
            
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(argc, argv, str)
    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(str)
    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(str)
    VALUE str;
{
    char *s, *t, *e;

    s = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    e = t = s + RSTRING(str)->len;
    /* remove spaces at head */
    while (s < t && ISSPACE(*s)) s++;

    if (s > RSTRING(str)->ptr) {
        rb_str_modify(str);
        RSTRING(str)->len = t-s;
        memmove(RSTRING(str)->ptr, s, RSTRING(str)->len);
        RSTRING(str)->ptr[RSTRING(str)->len] = '\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.

'hello'.match('(.)\1')      #=> #<MatchData:0x401b3d30>
'hello'.match('(.)\1')[0]   #=> "ll"
'hello'.match(/(.)\1/)[0]   #=> "ll"
'hello'.match('xx')         #=> nil
 
               static VALUE
rb_str_match_m(str, re)
    VALUE str, re;
{
    return rb_funcall(get_pat(re, 0), rb_intern("match"), 1, str);
}
            
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         #=> "**+"
 
               static VALUE
rb_str_succ(orig)
    VALUE orig;
{
    VALUE str;
    char *sbeg, *s;
    int c = -1;
    long n = 0;

    str = rb_str_new5(orig, RSTRING(orig)->ptr, RSTRING(orig)->len);
    OBJ_INFECT(str, orig);
    if (RSTRING(str)->len == 0) return str;

    sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;

    while (sbeg <= s) {
        if (ISALNUM(*s)) {
            if ((c = succ_char(s)) == 0) break;
            n = s - sbeg;
        }
        s--;
    }
    if (c == -1) {              /* str contains no alnum */
        sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
        c = '\001';
        while (sbeg <= s) {
            if ((*s += 1) != 0) break;
            s--;
        }
    }
    if (s < sbeg) {
        RESIZE_CAPA(str, RSTRING(str)->len + 1);
        s = RSTRING(str)->ptr + n;
        memmove(s+1, s, RSTRING(str)->len - n);
        *s = c;
        RSTRING(str)->len += 1;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
    }

    return str;
}
            
next! => str click to toggle source

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

 
               static VALUE
rb_str_succ_bang(str)
    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(str)
    VALUE str;
{
    return rb_str_to_inum(str, -8, Qfalse);
}
            
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"
 
               static VALUE
rb_str_replace(str, str2)
    VALUE str, str2;
{
    if (str == str2) return str;

    StringValue(str2);
    if (FL_TEST(str2, ELTS_SHARED)) {
        if (str_independent(str)) {
            free(RSTRING(str)->ptr);
        }
        RSTRING(str)->len = RSTRING(str2)->len;
        RSTRING(str)->ptr = RSTRING(str2)->ptr;
        FL_SET(str, ELTS_SHARED);
        FL_UNSET(str, STR_ASSOC);
        RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
    }
    else {
        if (str_independent(str)) {
            rb_str_resize(str, RSTRING(str2)->len);
            memcpy(RSTRING(str)->ptr, RSTRING(str2)->ptr, RSTRING(str2)->len);
            if (!RSTRING(str)->ptr) {
                make_null_str(str);
            }
        }
        else {
            RSTRING(str)->ptr = RSTRING(str2)->ptr;
            RSTRING(str)->len = RSTRING(str2)->len;
            str_make_independent(str);
        }
        if (FL_TEST(str2, STR_ASSOC)) {
            FL_SET(str, STR_ASSOC);
            RSTRING(str)->aux.shared = RSTRING(str2)->aux.shared;
        }
    }

    OBJ_INFECT(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(str)
    VALUE str;
{
    VALUE obj;
    char *s, *e, *p;

    if (RSTRING(str)->len <= 1) return rb_str_dup(str);

    obj = rb_str_new5(str, 0, RSTRING(str)->len);
    s = RSTRING(str)->ptr; e = s + RSTRING(str)->len - 1;
    p = RSTRING(obj)->ptr;

    while (e >= s) {
        *p++ = *e--;
    }
    OBJ_INFECT(obj, str);

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

Reverses str in place.

 
               static VALUE
rb_str_reverse_bang(str)
    VALUE str;
{
    char *s, *e;
    char c;

    if (RSTRING(str)->len > 1) {
        rb_str_modify(str);
        s = RSTRING(str)->ptr;
        e = s + RSTRING(str)->len - 1;
        while (s < e) {
            c = *s;
            *s++ = *e;
            *e-- = c;
        }
    }
    return str;
}
            
rindex(substring [, fixnum]) => fixnum or nil click to toggle source
rindex(fixnum [, fixnum]) => fixnum or nil
rindex(regexp [, fixnum]) => fixnum or nil

Returns the index of the last occurrence of the given substring, character (fixnum), 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(101)             #=> 1
"hello".rindex(/[aeiou]/, -2)   #=> 1
 
               static VALUE
rb_str_rindex_m(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE sub;
    VALUE position;
    long pos;

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

    switch (TYPE(sub)) {
      case T_REGEXP:
        if (RREGEXP(sub)->len) {
            pos = rb_reg_adjust_startpos(sub, str, pos, 1);
            pos = rb_reg_search(sub, str, pos, 1);
        }
        if (pos >= 0) return LONG2NUM(pos);
        break;

      case T_STRING:
        pos = rb_str_rindex(str, sub, pos);
        if (pos >= 0) return LONG2NUM(pos);
        break;

      case T_FIXNUM:
      {
          int c = FIX2INT(sub);
          unsigned char *p = (unsigned char*)RSTRING(str)->ptr + pos;
          unsigned char *pbeg = (unsigned char*)RSTRING(str)->ptr;

          if (pos == RSTRING(str)->len) {
              if (pos == 0) return Qnil;
              --p;
          }
          while (pbeg <= p) {
              if (*p == c) return LONG2NUM((char*)p - RSTRING(str)->ptr);
              p--;
          }
          return Qnil;
      }

      default:
        rb_raise(rb_eTypeError, "type mismatch: %s given",
                 rb_obj_classname(sub));
    }
    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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    return rb_str_justify(argc, argv, str, 'r');
}
            
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(str)
    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(str)
    VALUE str;
{
    char *s, *t, *e;

    s = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    e = t = s + RSTRING(str)->len;

    /* remove trailing '\0's */
    while (s < t && t[-1] == '\0') t--;

    /* remove trailing spaces */
    while (s < t && ISSPACE(*(t-1))) t--;

    if (t < e) {
        rb_str_modify(str);
        RSTRING(str)->len = t-s;
        RSTRING(str)->ptr[RSTRING(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(str, pat)
    VALUE str, pat;
{
    VALUE result;
    long start = 0;
    VALUE match = Qnil;
    char *p = RSTRING(str)->ptr; long len = RSTRING(str)->len;

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

        while (!NIL_P(result = scan_once(str, pat, &start))) {
            match = rb_backref_get();
            rb_ary_push(ary, result);
        }
        rb_backref_set(match);
        return ary;
    }

    while (!NIL_P(result = scan_once(str, pat, &start))) {
        match = rb_backref_get();
        rb_match_busy(match);
        rb_yield(result);
        str_mod_check(str, p, len);
        rb_backref_set(match); /* restore $~ value */
    }
    rb_backref_set(match);
    return str;
}
            
length => integer click to toggle source

Returns the length of str.

 
               static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}
            
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(regexp, fixnum) => new_str or nil
slice(other_str) => new_str or nil

Element Reference—If passed a single Fixnum, returns the code of the 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]                   #=> 101
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(argc, argv, str)
    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. 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.

string = "this is a string"
string.slice!(2)        #=> 105
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
string                  #=> "thing"
 
               static VALUE
rb_str_slice_bang(argc, argv, str)
    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];
    }
    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 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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE spat;
    VALUE limit;
    int awk_split = Qfalse;
    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(str)->len == 0)
                return rb_ary_new2(0);
            return rb_ary_new3(1, str);
        }
        i = 1;
    }

    if (NIL_P(spat)) {
        if (!NIL_P(rb_fs)) {
            spat = rb_fs;
            goto fs_set;
        }
        awk_split = Qtrue;
    }
    else {
      fs_set:
        if (TYPE(spat) == T_STRING && RSTRING(spat)->len == 1) {
            if (RSTRING(spat)->ptr[0] == ' ') {
                awk_split = Qtrue;
            }
            else {
                spat = rb_reg_regcomp(rb_reg_quote(spat));
            }
        }
        else {
            spat = get_pat(spat, 1);
        }
    }

    result = rb_ary_new();
    beg = 0;
    if (awk_split) {
        char *ptr = RSTRING(str)->ptr;
        long len = RSTRING(str)->len;
        char *eptr = ptr + len;
        int skip = 1;

        for (end = beg = 0; ptr<eptr; ptr++) {
            if (skip) {
                if (ISSPACE(*ptr)) {
                    beg++;
                }
                else {
                    end = beg+1;
                    skip = 0;
                    if (!NIL_P(limit) && lim <= i) break;
                }
            }
            else {
                if (ISSPACE(*ptr)) {
                    rb_ary_push(result, rb_str_substr(str, beg, end-beg));
                    skip = 1;
                    beg = end + 1;
                    if (!NIL_P(limit)) ++i;
                }
                else {
                    end++;
                }
            }
        }
    }
    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(rb_backref_get())->regs;
            if (start == end && BEG(0) == END(0)) {
                if (!RSTRING(str)->ptr) {
                    rb_ary_push(result, rb_str_new("", 0));
                    break;
                }
                else if (last_null == 1) {
                    rb_ary_push(result, rb_str_substr(str, beg, mbclen2(RSTRING(str)->ptr[beg],spat)));
                    beg = start;
                }
                else {
                    start += mbclen2(RSTRING(str)->ptr[start],spat);
                    last_null = 1;
                    continue;
                }
            }
            else {
                rb_ary_push(result, rb_str_substr(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_substr(str, BEG(idx), END(idx)-BEG(idx));
                rb_ary_push(result, tmp);
            }
            if (!NIL_P(limit) && lim <= ++i) break;
        }
    }
    if (RSTRING(str)->len > 0 && (!NIL_P(limit) || RSTRING(str)->len > beg || lim < 0)) {
        if (RSTRING(str)->len == beg)
            tmp = rb_str_new5(str, 0, 0);
        else
            tmp = rb_str_substr(str, beg, RSTRING(str)->len-beg);
        rb_ary_push(result, tmp);
    }
    if (NIL_P(limit) && lim == 0) {
        while (RARRAY(result)->len > 0 &&
               RSTRING(RARRAY(result)->ptr[RARRAY(result)->len-1])->len == 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(argc, argv, str)
    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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    char squeez[256];
    char *s, *send, *t;
    int c, save, modify = 0;
    int init = 1;
    int i;

    if (argc == 0) {
        for (i=0; i<256; i++) {
            squeez[i] = 1;
        }
    }
    else {
        for (i=0; i<argc; i++) {
            VALUE s = argv[i];

            StringValue(s);
            tr_setup_table(s, squeez, init);
            init = 0;
        }
    }

    rb_str_modify(str);
    s = t = RSTRING(str)->ptr;
    if (!s || RSTRING(str)->len == 0) return Qnil;
    send = s + RSTRING(str)->len;
    save = -1;
    while (s < send) {
        c = *s++ & 0xff;
        if (c != save || !squeez[c]) {
            *t++ = save = c;
        }
    }
    *t = '\0';
    if (t - RSTRING(str)->ptr != RSTRING(str)->len) {
        RSTRING(str)->len = t - RSTRING(str)->ptr;
        modify = 1;
    }

    if (modify) return str;
    return Qnil;
}
            
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(str)
    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(str)
    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, 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].to_s + ' ' }   #=> "104 ello"
 
               static VALUE
rb_str_sub(argc, argv, str)
    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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE pat, repl, match;
    struct re_registers *regs;
    int iter = 0;
    int tainted = 0;
    long plen;

    if (argc == 1 && rb_block_given_p()) {
        iter = 1;
    }
    else if (argc == 2) {
        repl = argv[1];
        StringValue(repl);
        if (OBJ_TAINTED(repl)) tainted = 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) {
        match = rb_backref_get();
        regs = RMATCH(match)->regs;

        if (iter) {
            char *p = RSTRING(str)->ptr; long len = RSTRING(str)->len;

            rb_match_busy(match);
            repl = rb_obj_as_string(rb_yield(rb_reg_nth_match(0, match)));
            str_mod_check(str, p, len);
            str_frozen_check(str);
            rb_backref_set(match);
        }
        else {
            repl = rb_reg_regsub(repl, str, regs);
        }
        rb_str_modify(str);
        if (OBJ_TAINTED(repl)) tainted = 1;
        plen = END(0) - BEG(0);
        if (RSTRING(repl)->len > plen) {
            RESIZE_CAPA(str, RSTRING(str)->len + RSTRING(repl)->len - plen);
        }
        if (RSTRING(repl)->len != plen) {
            memmove(RSTRING(str)->ptr + BEG(0) + RSTRING(repl)->len,
                    RSTRING(str)->ptr + BEG(0) + plen,
                    RSTRING(str)->len - BEG(0) - plen);
        }
        memcpy(RSTRING(str)->ptr + BEG(0),
               RSTRING(repl)->ptr, RSTRING(repl)->len);
        RSTRING(str)->len += RSTRING(repl)->len - plen;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
        if (tainted) OBJ_TAINT(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         #=> "**+"
 
               static VALUE
rb_str_succ(orig)
    VALUE orig;
{
    VALUE str;
    char *sbeg, *s;
    int c = -1;
    long n = 0;

    str = rb_str_new5(orig, RSTRING(orig)->ptr, RSTRING(orig)->len);
    OBJ_INFECT(str, orig);
    if (RSTRING(str)->len == 0) return str;

    sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;

    while (sbeg <= s) {
        if (ISALNUM(*s)) {
            if ((c = succ_char(s)) == 0) break;
            n = s - sbeg;
        }
        s--;
    }
    if (c == -1) {              /* str contains no alnum */
        sbeg = RSTRING(str)->ptr; s = sbeg + RSTRING(str)->len - 1;
        c = '\001';
        while (sbeg <= s) {
            if ((*s += 1) != 0) break;
            s--;
        }
    }
    if (s < sbeg) {
        RESIZE_CAPA(str, RSTRING(str)->len + 1);
        s = RSTRING(str)->ptr + n;
        memmove(s+1, s, RSTRING(str)->len - n);
        *s = c;
        RSTRING(str)->len += 1;
        RSTRING(str)->ptr[RSTRING(str)->len] = '\0';
    }

    return str;
}
            
succ! => str click to toggle source

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

 
               static VALUE
rb_str_succ_bang(str)
    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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE vbits;
    int bits;
    char *ptr, *p, *pend;
    long len;

    if (rb_scan_args(argc, argv, "01", &vbits) == 0) {
        bits = 16;
    }
    else bits = NUM2INT(vbits);

    ptr = p = RSTRING(str)->ptr;
    len = RSTRING(str)->len;
    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.

"Hello".swapcase          #=> "hELLO"
"cYbEr_PuNk11".swapcase   #=> "CyBeR_pUnK11"
 
               static VALUE
rb_str_swapcase(str)
    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.

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

    rb_str_modify(str);
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    while (s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISUPPER(*s)) {
            *s = tolower(*s);
            modify = 1;
        }
        else if (ISLOWER(*s)) {
            *s = toupper(*s);
            modify = 1;
        }
        s++;
    }

    if (modify) return str;
    return Qnil;
}
            
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(str)
    VALUE str;
{
    return rb_float_new(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 (2, 8, 10, or 16). 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(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE b;
    int base;

    rb_scan_args(argc, argv, "01", &b);
    if (argc == 0) base = 10;
    else base = NUM2INT(b);

    if (base < 0) {
        rb_raise(rb_eArgError, "illegal radix %d", base);
    }
    return rb_str_to_inum(str, base, Qfalse);
}
            
to_s => str click to toggle source
to_str => str

Returns the receiver.

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

Returns the receiver.

 
               static VALUE
rb_str_to_s(str)
    VALUE str;
{
    if (rb_obj_class(str) != rb_cString) {
        VALUE dup = str_alloc(rb_cString);
        rb_str_replace(dup, str);
        return dup;
    }
    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(s)
    VALUE s;
{
    volatile VALUE str = s;
    ID id;

    if (!RSTRING(str)->ptr || RSTRING(str)->len == 0) {
        rb_raise(rb_eArgError, "interning empty string");
    }
    if (strlen(RSTRING(str)->ptr) != RSTRING(str)->len)
        rb_raise(rb_eArgError, "symbol string may not contain `\\0'");
    if (OBJ_TAINTED(str) && rb_safe_level() >= 1 && !rb_sym_interned_p(str)) {
        rb_raise(rb_eSecurityError, "Insecure: can't intern tainted string");
    }
    id = rb_intern(RSTRING(str)->ptr);
    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(str, src, repl)
    VALUE str, src, 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(str, src, repl)
    VALUE str, src, 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(str, src, repl)
    VALUE str, src, 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(str, src, repl)
    VALUE str, src, 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  | with trailing nulls and spaces removed
-------+---------+-----------------------------------------
  a    | String  | string
-------+---------+-----------------------------------------
  B    | String  | extract bits from each character (msb first)
-------+---------+-----------------------------------------
  b    | String  | extract bits from each character (lsb first)
-------+---------+-----------------------------------------
  C    | Fixnum  | extract a character as an unsigned integer
-------+---------+-----------------------------------------
  c    | Fixnum  | extract a character 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
-------+---------+-----------------------------------------
  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(str, fmt)
    VALUE str, fmt;
{
    static char *hexdigits = "0123456789abcdef0123456789ABCDEFx";
    char *s, *send;
    char *p, *pend;
    VALUE ary;
    char type;
    long len;
    int tmp, star;
#ifdef NATINT_PACK
    int natint;                 /* native integer */
#endif

    StringValue(str);
    StringValue(fmt);
    s = RSTRING(str)->ptr;
    send = s + RSTRING(str)->len;
    p = RSTRING(fmt)->ptr;
    pend = p + RSTRING(fmt)->len;

    ary = 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 == '!') {
            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)) {
            len = strtoul(p, (char**)&p, 10);
        }
        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--;
                }
                rb_ary_push(ary, 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++;
                rb_ary_push(ary, 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;
            rb_ary_push(ary, 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;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                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;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                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;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                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;
                rb_ary_push(ary, bitstr = rb_str_new(0, len));
                t = RSTRING(bitstr)->ptr;
                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;
                rb_ary_push(ary, INT2FIX(c));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'C':
            PACK_LENGTH_ADJUST(unsigned char,sizeof(unsigned char));
            while (len-- > 0) {
                unsigned char c = *s++;
                rb_ary_push(ary, 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);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, ULONG2NUM(tmp));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'q':
            PACK_LENGTH_ADJUST_SIZE(QUAD_SIZE);
            while (len-- > 0) {
                char *tmp = (char*)s;
                s += QUAD_SIZE;
                rb_ary_push(ary, 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;
                rb_ary_push(ary, 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);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, ULONG2NUM(ntohl(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'v':
            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);
                rb_ary_push(ary, UINT2NUM(vtohs(tmp)));
            }
            PACK_ITEM_ADJUST();
            break;

          case 'V':
            PACK_LENGTH_ADJUST(unsigned long,4);
            while (len-- > 0) {
                unsigned long tmp = 0;
                memcpy(OFF32(&tmp), s, NATINT_LEN(long,4));
                s += NATINT_LEN(long,4);
                rb_ary_push(ary, 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);
                rb_ary_push(ary, rb_float_new((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);
                rb_ary_push(ary, rb_float_new((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);
                rb_ary_push(ary, rb_float_new(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);
                rb_ary_push(ary, rb_float_new(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);
                rb_ary_push(ary, rb_float_new((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);
                rb_ary_push(ary, rb_float_new(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--;
                rb_ary_push(ary, ULONG2NUM(l));
            }
            break;

          case 'u':
            {
                VALUE buf = infected_str_new(0, (send - s)*3/4, str);
                char *ptr = RSTRING(buf)->ptr;
                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(buf)->len) {
                        len -= total - RSTRING(buf)->len;
                        total = RSTRING(buf)->len;
                    }

                    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 */
                }
                
                RSTRING(buf)->ptr[total] = '\0';
                RSTRING(buf)->len = total;
                rb_ary_push(ary, buf);
            }
            break;

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

                if (first) {
                    int i;
                    first = 0;

                    for (i = 0; i < 256; i++) {
                        b64_xtable[i] = -1;
                    }
                    for (i = 0; i < 64; i++) {
                        b64_xtable[(int)b64_table[i]] = i;
                    }
                }
                while (s < send) {
                    a = b = c = d = -1;
                    while((a = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { s++; }
                    if( s >= send ) break;
                    s++;
                    while((b = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { s++; }
                    if( s >= send ) break;
                    s++;
                    while((c = b64_xtable[(int)(*(unsigned char*)s)]) == -1 && s < send) { if( *s == '=' ) break; s++; }
                    if( *s == '=' || s >= send ) break;
                    s++;
                    while((d = b64_xtable[(int)(*(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;
                    }
                }
                *ptr = '\0';
                RSTRING(buf)->len = ptr - RSTRING(buf)->ptr;
                rb_ary_push(ary, buf);
            }
            break;

          case 'M':
            {
                VALUE buf = infected_str_new(0, send - s, str);
                char *ptr = RSTRING(buf)->ptr;
                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++;
                }
                *ptr = '\0';
                RSTRING(buf)->len = ptr - RSTRING(buf)->ptr;
                rb_ary_push(ary, buf);
            }
            break;

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

          case 'X':
            if (len > s - RSTRING(str)->ptr)
                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) {
                char *t;
                VALUE tmp;

                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(a)->ptr;
                    pend = p + RARRAY(a)->len;
                    while (p < pend) {
                        if (TYPE(*p) == T_STRING && RSTRING(*p)->ptr == t) {
                            if (len < RSTRING(*p)->len) {
                                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");
                    }
                }
                else {
                    tmp = Qnil;
                }
                rb_ary_push(ary, 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;
                    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(a)->ptr;
                        pend = p + RARRAY(a)->len;
                        while (p < pend) {
                            if (TYPE(*p) == T_STRING && RSTRING(*p)->ptr == t) {
                                tmp = *p;
                                break;
                            }
                            p++;
                        }
                        if (p == pend) {
                            rb_raise(rb_eArgError, "non associated pointer");
                        }
                    }
                    else {
                        tmp = Qnil;
                    }
                    rb_ary_push(ary, 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)) {
                        rb_ary_push(ary, 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)) {
                                rb_ary_push(ary, 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.

"hEllO".upcase   #=> "HELLO"
 
               static VALUE
rb_str_upcase(str)
    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.

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

    rb_str_modify(str);
    s = RSTRING(str)->ptr; send = s + RSTRING(str)->len;
    while (s < send) {
        if (ismbchar(*s)) {
            s+=mbclen(*s) - 1;
        }
        else if (ISLOWER(*s)) {
            *s = toupper(*s);
            modify = 1;
        }
        s++;
    }

    if (modify) return str;
    return Qnil;
}
            
upto(other_str) {|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.

"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_m(beg, end)
    VALUE beg, end;
{
    return rb_str_upto(beg, end, Qfalse);
}