Class: String

Inherits:
Object show all
Includes:
Comparable, Enumerable
Defined in:
string.c

Instance Method Summary collapse

Methods included from Comparable

#<, #<=, #>, #>=, #between?

Methods included from Enumerable

#all?, #any?, #collect, #cycle, #detect, #drop, #drop_while, #each_cons, #each_slice, #each_with_index, #entries, #enum_cons, #enum_slice, #enum_with_index, #find, #find_all, #find_index, #first, #grep, #group_by, #inject, #map, #max, #max_by, #member?, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #reduce, #reject, #reverse_each, #select, #sort, #sort_by, #take, #take_while, #to_a, #zip

Constructor Details

#new(str = "") ⇒ String

Returns a new string object containing a copy of str.



# File 'string.c'

/*
 *  call-seq:
 *     String.new(str="")   => new_str
 *  
 *  Returns a new string object containing a copy of <i>str</i>.
 */

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;
}

Instance Method Details

#%(arg) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str % arg   => new_str
 *  
 *  Format---Uses <i>str</i> as a format specification, and returns the result
 *  of applying it to <i>arg</i>. If the format specification contains more than
 *  one substitution, then <i>arg</i> must be an <code>Array</code> containing
 *  the values to be substituted. See <code>Kernel::sprintf</code> 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);
}

#*(integer) ⇒ String

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

"Ho! " * 3   #=> "Ho! Ho! Ho! "

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str * integer   => new_str
 *  
 *  Copy---Returns a new <code>String</code> containing <i>integer</i> 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;
}

#+(other_str) ⇒ String

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

"Hello from " + self.to_s   #=> "Hello from main"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str + other_str   => new_str
 *  
 *  Concatenation---Returns a new <code>String</code> containing
 *  <i>other_str</i> concatenated to <i>str</i>.
 *     
 *     "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;
}

#<<(fixnum) ⇒ String #concat(fixnum) ⇒ String #<<(obj) ⇒ String #concat(obj) ⇒ String

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!"

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str << fixnum        => str
 *     str.concat(fixnum)   => str
 *     str << obj           => str
 *     str.concat(obj)      => str
 *  
 *  Append---Concatenates the given object to <i>str</i>. If the object is a
 *  <code>Fixnum</code> 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;
}

#<=>(other_str) ⇒ -1, ...

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

Returns:

  • (-1, 0, +1)


# File 'string.c'

/*
 *  call-seq:
 *     str <=> other_str   => -1, 0, +1
 *  
 *  Comparison---Returns -1 if <i>other_str</i> is less than, 0 if
 *  <i>other_str</i> is equal to, and +1 if <i>other_str</i> is greater than
 *  <i>str</i>. 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 <code>$=</code> is
 *  <code>false</code>, the comparison is based on comparing the binary values
 *  of each character in the string. In older versions of Ruby, setting
 *  <code>$=</code> allowed case-insensitive comparisons; this is now deprecated
 *  in favor of using <code>String#casecmp</code>.
 *
 *  <code><=></code> is the basis for the methods <code><</code>,
 *  <code><=</code>, <code>></code>, <code>>=</code>, and <code>between?</code>,
 *  included from module <code>Comparable</code>.  The method
 *  <code>String#==</code> does not use <code>Comparable#==</code>.
 *     
 *     "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);
}

#==(obj) ⇒ Boolean

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

Returns:

  • (Boolean)


# File 'string.c'

/*
 *  call-seq:
 *     str == obj   => true or false
 *  
 *  Equality---If <i>obj</i> is not a <code>String</code>, returns
 *  <code>false</code>. Otherwise, returns <code>true</code> if <i>str</i>
 *  <code><=></code> <i>obj</i> 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;
}

#=~(obj) ⇒ Fixnum?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str =~ obj   => fixnum or nil
 *  
 *  Match---If <i>obj</i> is a <code>Regexp</code>, use it as a pattern to match
 *  against <i>str</i>,and returns the position the match starts, or 
 *  <code>nil</code> if there is no match. Otherwise, invokes
 *  <i>obj.=~</i>, passing <i>str</i> as an argument. The default
 *  <code>=~</code> in <code>Object</code> returns <code>false</code>.
 *     
 *     "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);
    }
}

#[](fixnum) ⇒ Fixnum? #[](fixnum, fixnum) ⇒ String? #[](range) ⇒ String? #[](regexp) ⇒ String? #[](regexp, fixnum) ⇒ String? #[](other_str) ⇒ String? #slice(fixnum) ⇒ Fixnum? #slice(fixnum, fixnum) ⇒ String? #slice(range) ⇒ String? #slice(regexp) ⇒ String? #slice(regexp, fixnum) ⇒ String? #slice(other_str) ⇒ String?

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

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str[fixnum]                 => fixnum or nil
 *     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
 *     str.slice(fixnum)           => fixnum or nil
 *     str.slice(fixnum, fixnum)   => new_str or nil
 *     str.slice(range)            => new_str or nil
 *     str.slice(regexp)           => new_str or nil
 *     str.slice(regexp, fixnum)   => new_str or nil
 *     str.slice(other_str)        => new_str or nil
 *  
 *  Element Reference---If passed a single <code>Fixnum</code>, returns the code
 *  of the character at that position. If passed two <code>Fixnum</code>
 *  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 <i>str</i>. Returns
 *  <code>nil</code> 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 <code>Regexp</code> is supplied, the matching portion of <i>str</i> is
 *  returned. If a numeric parameter follows the regular expression, that
 *  component of the <code>MatchData</code> is returned instead. If a
 *  <code>String</code> is given, that string is returned if it occurs in
 *  <i>str</i>. In both cases, <code>nil</code> 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]);
}

#[]=(fixnum) ⇒ Object #[]=(fixnum) ⇒ Object #[]=(fixnum, fixnum) ⇒ Object #[]=(range) ⇒ Object #[]=(regexp) ⇒ Object #[]=(regexp, fixnum) ⇒ Object #[]=(other_str) ⇒ Object

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.



# File 'string.c'

/*
 *  call-seq:
 *     str[fixnum] = fixnum
 *     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 <i>str</i>. The
 *  portion of the string affected is determined using the same criteria as
 *  <code>String#[]</code>. 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, <code>IndexError</code> is raised. If the regular expression
 *  form is used, the optional second <code>Fixnum</code> allows you to specify
 *  which portion of the match to replace (effectively using the
 *  <code>MatchData</code> indexing rules. The forms that take a
 *  <code>Fixnum</code> will raise an <code>IndexError</code> if the value is
 *  out of range; the <code>Range</code> form will raise a
 *  <code>RangeError</code>, and the <code>Regexp</code> and <code>String</code>
 *  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]);
}

#bytesEnumerator #bytes {|fixnum| ... } ⇒ String

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

"hello".bytes.to_a        #=> [104, 101, 108, 108, 111]

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.each_byte {|fixnum| block }    => str
 *  
 *  Passes each byte in <i>str</i> to the given block.
 *     
 *     "hello".each_byte {|c| print c, ' ' }
 *     
 *  <em>produces:</em>
 *     
 *     104 101 108 108 111
 */

static VALUE
rb_str_each_byte(str)
    VALUE str;
{
    long i;

    RETURN_ENUMERATOR(str, 0, 0);
    for (i=0; i<RSTRING(str)->len; i++) {
    rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff));
    }
    return str;
}

#lengthInteger

Returns the length of str.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.length   => integer
 *  
 *  Returns the length of <i>str</i>.
 */

static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}

#capitalizeString

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.capitalize   => new_str
 *  
 *  Returns a copy of <i>str</i> 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!String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.capitalize!   => str or nil
 *  
 *  Modifies <i>str</i> by converting the first character to uppercase and the
 *  remainder to lowercase. Returns <code>nil</code> 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, ...

Case-insensitive version of String#<=>.

"abcdef".casecmp("abcde")     #=> 1
"aBcDeF".casecmp("abcdef")    #=> 0
"abcdef".casecmp("abcdefg")   #=> -1
"abcdef".casecmp("ABCDEF")    #=> 0

Returns:

  • (-1, 0, +1)


# File 'string.c'

/*
 *  call-seq:
 *     str.casecmp(other_str)   => -1, 0, +1
 *  
 *  Case-insensitive version of <code>String#<=></code>.
 *     
 *     "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) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.center(integer, padstr)   => new_str
 *  
 *  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
 *  <code>String</code> of length <i>integer</i> with <i>str</i> centered and
 *  padded with <i>padstr</i>; otherwise, returns <i>str</i>.
 *     
 *     "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');
}

#charsEnumerator #chars {|substr| ... } ⇒ String

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

"foo".chars.to_a   #=> ["f","o","o"]

Overloads:



# File 'string.c'

/*
 *  Document-method: each_char
 *  call-seq:
 *     str.each_char {|cstr| block }    => str
 *  
 *  Passes each character in <i>str</i> to the given block.
 *     
 *     "hello".each_char {|c| print c, ' ' }
 *     
 *  <em>produces:</em>
 *     
 *     h e l l o 
 */

static VALUE
rb_str_each_char(VALUE str)
{
    int i, len, n;
    const char *ptr;

    RETURN_ENUMERATOR(str, 0, 0);
    str = rb_str_new4(str);
    ptr = RSTRING(str)->ptr;
    len = RSTRING(str)->len;
    for (i = 0; i < len; i += n) {
        n = mbclen(ptr[i]);
        rb_yield(rb_str_substr(str, i, n));
    }
    return str;
}

#chomp(separator = $/) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.chomp(separator=$/)   => new_str
 *  
 *  Returns a new <code>String</code> with the given record separator removed
 *  from the end of <i>str</i> (if present). If <code>$/</code> has not been
 *  changed from the default Ruby record separator, then <code>chomp</code> also
 *  removes carriage return characters (that is it will remove <code>\n</code>,
 *  <code>\r</code>, and <code>\r\n</code>).
 *     
 *     "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 = $/) ⇒ String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.chomp!(separator=$/)   => str or nil
 *  
 *  Modifies <i>str</i> in place as described for <code>String#chomp</code>,
 *  returning <i>str</i>, or <code>nil</code> 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;
}

#chopString

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       #=> ""

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.chop   => new_str
 *  
 *  Returns a new <code>String</code> with the last character removed.  If the
 *  string ends with <code>\r\n</code>, both characters are removed. Applying
 *  <code>chop</code> to an empty string returns an empty
 *  string. <code>String#chomp</code> 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!String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.chop!   => str or nil
 *  
 *  Processes <i>str</i> as for <code>String#chop</code>, returning <i>str</i>,
 *  or <code>nil</code> if <i>str</i> is the empty string.  See also
 *  <code>String#chomp!</code>.
 */

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;
}

#<<(fixnum) ⇒ String #concat(fixnum) ⇒ String #<<(obj) ⇒ String #concat(obj) ⇒ String

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!"

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str << fixnum        => str
 *     str.concat(fixnum)   => str
 *     str << obj           => str
 *     str.concat(obj)      => str
 *  
 *  Append---Concatenates the given object to <i>str</i>. If the object is a
 *  <code>Fixnum</code> 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

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.count([other_str]+)   => fixnum
 *  
 *  Each <i>other_str</i> parameter defines a set of characters to count.  The
 *  intersection of these sets defines the characters to count in
 *  <i>str</i>. Any <i>other_str</i> 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) ⇒ String

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./].

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.crypt(other_str)   => new_str
 *  
 *  Applies a one-way cryptographic hash to <i>str</i> by invoking the standard
 *  library function <code>crypt</code>. The argument is the salt string, which
 *  should be two characters long, each character drawn from
 *  <code>[a-zA-Z0-9./]</code>.
 */

static VALUE
rb_str_crypt(str, salt)
    VALUE str, salt;
{
    extern char *crypt _((const char *, const char*));
    VALUE result;
    const 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]) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.delete([other_str]+)   => new_str
 *  
 *  Returns a copy of <i>str</i> with all characters in the intersection of its
 *  arguments deleted. Uses the same rules for building the set of characters as
 *  <code>String#count</code>.
 *     
 *     "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]) ⇒ String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.delete!([other_str]+>)   => str or nil
 *  
 *  Performs a <code>delete</code> operation in place, returning <i>str</i>, or
 *  <code>nil</code> if <i>str</i> 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;
}

#downcaseString

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.downcase   => new_str
 *  
 *  Returns a copy of <i>str</i> 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!String?

Downcases the contents of str, returning nil if no changes were made.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.downcase!   => str or nil
 *  
 *  Downcases the contents of <i>str</i>, returning <code>nil</code> 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;
}

#dumpString

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.dump   => new_str
 *  
 *  Produces a version of <i>str</i> with all nonprinting characters replaced by
 *  <code>\nnn</code> 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| ... } ⇒ String #each_line(separator = $/) {|substr| ... } ⇒ String

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

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

produces:

Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"

Overloads:

  • #each(separator = $/) {|substr| ... } ⇒ String

    Yields:

    • (substr)

    Returns:

  • #each_line(separator = $/) {|substr| ... } ⇒ String

    Yields:

    • (substr)

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.each(separator=$/) {|substr| block }        => str
 *     str.each_line(separator=$/) {|substr| block }   => str
 *  
 *  Splits <i>str</i> using the supplied parameter as the record separator
 *  (<code>$/</code> by default), passing each substring in turn to the supplied
 *  block. If a zero-length record separator is supplied, the string is split
 *  into paragraphs delimited by multiple successive newlines.
 *     
 *     print "Example one\n"
 *     "hello\nworld".each {|s| p s}
 *     print "Example two\n"
 *     "hello\nworld".each('l') {|s| p s}
 *     print "Example three\n"
 *     "hello\n\n\nworld".each('') {|s| p s}
 *     
 *  <em>produces:</em>
 *     
 *     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;
    }
    RETURN_ENUMERATOR(str, argc, argv);
    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| ... } ⇒ String

Passes each byte in str to the given block.

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

produces:

104 101 108 108 111

Yields:

  • (fixnum)

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.each_byte {|fixnum| block }    => str
 *  
 *  Passes each byte in <i>str</i> to the given block.
 *     
 *     "hello".each_byte {|c| print c, ' ' }
 *     
 *  <em>produces:</em>
 *     
 *     104 101 108 108 111
 */

static VALUE
rb_str_each_byte(str)
    VALUE str;
{
    long i;

    RETURN_ENUMERATOR(str, 0, 0);
    for (i=0; i<RSTRING(str)->len; i++) {
    rb_yield(INT2FIX(RSTRING(str)->ptr[i] & 0xff));
    }
    return str;
}

#each_char {|cstr| ... } ⇒ String

Passes each character in str to the given block.

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

produces:

h e l l o

Yields:

  • (cstr)

Returns:



# File 'string.c'

/*
 *  Document-method: each_char
 *  call-seq:
 *     str.each_char {|cstr| block }    => str
 *  
 *  Passes each character in <i>str</i> to the given block.
 *     
 *     "hello".each_char {|c| print c, ' ' }
 *     
 *  <em>produces:</em>
 *     
 *     h e l l o 
 */

static VALUE
rb_str_each_char(VALUE str)
{
    int i, len, n;
    const char *ptr;

    RETURN_ENUMERATOR(str, 0, 0);
    str = rb_str_new4(str);
    ptr = RSTRING(str)->ptr;
    len = RSTRING(str)->len;
    for (i = 0; i < len; i += n) {
        n = mbclen(ptr[i]);
        rb_yield(rb_str_substr(str, i, n));
    }
    return str;
}

#each(separator = $/) {|substr| ... } ⇒ String #each_line(separator = $/) {|substr| ... } ⇒ String

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

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

produces:

Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"

Overloads:

  • #each(separator = $/) {|substr| ... } ⇒ String

    Yields:

    • (substr)

    Returns:

  • #each_line(separator = $/) {|substr| ... } ⇒ String

    Yields:

    • (substr)

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.each(separator=$/) {|substr| block }        => str
 *     str.each_line(separator=$/) {|substr| block }   => str
 *  
 *  Splits <i>str</i> using the supplied parameter as the record separator
 *  (<code>$/</code> by default), passing each substring in turn to the supplied
 *  block. If a zero-length record separator is supplied, the string is split
 *  into paragraphs delimited by multiple successive newlines.
 *     
 *     print "Example one\n"
 *     "hello\nworld".each {|s| p s}
 *     print "Example two\n"
 *     "hello\nworld".each('l') {|s| p s}
 *     print "Example three\n"
 *     "hello\n\n\nworld".each('') {|s| p s}
 *     
 *  <em>produces:</em>
 *     
 *     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;
    }
    RETURN_ENUMERATOR(str, argc, argv);
    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?Boolean

Returns true if str has a length of zero.

"hello".empty?   #=> false
"".empty?        #=> true

Returns:

  • (Boolean)


# File 'string.c'

/*
 *  call-seq:
 *     str.empty?   => true or false
 *  
 *  Returns <code>true</code> if <i>str</i> 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;
}

#end_with?([suffix]) ⇒ Boolean

Returns true if str ends with the suffix given.

Returns:

  • (Boolean)


# File 'string.c'

/*
 *  call-seq:
 *     str.end_with?([suffix]+)   => true or false
 *  
 *  Returns true if <i>str</i> ends with the suffix given.
 */

static VALUE
rb_str_end_with(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    int i;
    long pos;
    VALUE pat;

    for (i=0; i<argc; i++) {
    VALUE suffix = rb_check_string_type(argv[i]);
    if (NIL_P(suffix)) continue;
    if (RSTRING(str)->len < RSTRING(suffix)->len) continue;
        pat = get_arg_pat(suffix);
        pos = rb_reg_adjust_startpos(pat, str, RSTRING(str)->len - RSTRING(suffix)->len, 0);
        if (rb_reg_search(pat, str, pos, 0) >= 0)
            return Qtrue;
    }
    return Qfalse;
}

#eql?(other) ⇒ Boolean

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

Returns:

  • (Boolean)


# File 'string.c'

/*
 * call-seq:
 *   str.eql?(other)   => true or false
 *
 * 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) ⇒ String #gsub(pattern) {|match| ... } ⇒ String

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 "

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.gsub(pattern, replacement)       => new_str
 *     str.gsub(pattern) {|match| block }   => new_str
 *  
 *  Returns a copy of <i>str</i> with <em>all</em> occurrences of <i>pattern</i>
 *  replaced with either <i>replacement</i> or the value of the block. The
 *  <i>pattern</i> will typically be a <code>Regexp</code>; if it is a
 *  <code>String</code> then no regular expression metacharacters will be
 *  interpreted (that is <code>/\d/</code> will match a digit, but
 *  <code>'\d'</code> will match a backslash followed by a 'd').
 *     
 *  If a string is used as the replacement, special variables from the match
 *  (such as <code>$&</code> and <code>$1</code>) cannot be substituted into it,
 *  as substitution into the string occurs before the pattern match
 *  starts. However, the sequences <code>\1</code>, <code>\2</code>, 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 <code>$1</code>, <code>$2</code>, <code>$`</code>,
 *  <code>$&</code>, and <code>$'</code> 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) ⇒ String? #gsub!(pattern) {|match| ... } ⇒ String?

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

Overloads:

  • #gsub!(pattern, replacement) ⇒ String?

    Returns:

  • #gsub!(pattern) {|match| ... } ⇒ String?

    Yields:

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.gsub!(pattern, replacement)        => str or nil
 *     str.gsub!(pattern) {|match| block }    => str or nil
 *  
 *  Performs the substitutions of <code>String#gsub</code> in place, returning
 *  <i>str</i>, or <code>nil</code> 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);
}

#hashFixnum

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

Returns:



# File 'string.c'

/*
 * call-seq:
 *    str.hash   => fixnum
 *
 * 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);
}

#hexInteger

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.hex   => integer
 *  
 *  Treats leading characters from <i>str</i> as a string of hexadecimal digits
 *  (with an optional sign and an optional <code>0x</code>) 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) ⇒ Boolean #include?(fixnum) ⇒ Boolean

Returns true if str contains the given string or character.

"hello".include? "lo"   #=> true
"hello".include? "ol"   #=> false
"hello".include? ?h     #=> true

Overloads:

  • #include?(other_str) ⇒ Boolean

    Returns:

    • (Boolean)
  • #include?(fixnum) ⇒ Boolean

    Returns:

    • (Boolean)


# File 'string.c'

/*
 *  call-seq:
 *     str.include? other_str   => true or false
 *     str.include? fixnum      => true or false
 *  
 *  Returns <code>true</code> if <i>str</i> 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? #index(fixnum[, offset]) ⇒ Fixnum? #index(regexp[, offset]) ⇒ Fixnum?

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

Overloads:

  • #index(substring[, offset]) ⇒ Fixnum?

    Returns:

  • #index(fixnum[, offset]) ⇒ Fixnum?

    Returns:

  • #index(regexp[, offset]) ⇒ Fixnum?

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.index(substring [, offset])   => fixnum or nil
 *     str.index(fixnum [, offset])      => fixnum or nil
 *     str.index(regexp [, offset])      => fixnum or nil
 *  
 *  Returns the index of the first occurrence of the given <i>substring</i>,
 *  character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>str</i>. Returns
 *  <code>nil</code> 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) ⇒ String

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

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.replace(other_str)   => str
 *  
 *  Replaces the contents and taintedness of <i>str</i> with the corresponding
 *  values in <i>other_str</i>.
 *     
 *     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) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.insert(index, other_str)   => str
 *  
 *  Inserts <i>other_str</i> before the character at the given
 *  <i>index</i>, modifying <i>str</i>. Negative indices count from the
 *  end of the string, and insert <em>after</em> the given character.
 *  The intent is insert <i>aString</i> so that it starts at the given
 *  <i>index</i>.
 *     
 *     "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;
}

#inspectString

Returns a printable version of str, with special characters escaped.

str = "hello"
str[3] = 8
str.inspect       #=> "hel\010o"

Returns:



# File 'string.c'

/*
 * call-seq:
 *   str.inspect   => string
 *
 * 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++;
    int len;
    if (ismbchar(c) && p - 1 + (len = mbclen(c)) <= pend) {
        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;
}

#internObject #to_symObject

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"


# File 'string.c'

/*
 *  call-seq:
 *     str.intern   => symbol
 *     str.to_sym   => symbol
 *  
 *  Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
 *  symbol if it did not previously exist. See <code>Symbol#id2name</code>.
 *     
 *     "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
 *  <code>:xxx</code> 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);
}

#lengthInteger

Returns the length of str.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.length   => integer
 *  
 *  Returns the length of <i>str</i>.
 */

static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}

#lines(separator = $/) ⇒ Enumerator #lines(separator = $/) {|substr| ... } ⇒ String

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

"foo\nbar\n".lines.to_a   #=> ["foo\n", "bar\n"]
"foo\nb ar".lines.sort    #=> ["b ar", "foo\n"]

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.each(separator=$/) {|substr| block }        => str
 *     str.each_line(separator=$/) {|substr| block }   => str
 *  
 *  Splits <i>str</i> using the supplied parameter as the record separator
 *  (<code>$/</code> by default), passing each substring in turn to the supplied
 *  block. If a zero-length record separator is supplied, the string is split
 *  into paragraphs delimited by multiple successive newlines.
 *     
 *     print "Example one\n"
 *     "hello\nworld".each {|s| p s}
 *     print "Example two\n"
 *     "hello\nworld".each('l') {|s| p s}
 *     print "Example three\n"
 *     "hello\n\n\nworld".each('') {|s| p s}
 *     
 *  <em>produces:</em>
 *     
 *     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;
    }
    RETURN_ENUMERATOR(str, argc, argv);
    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;
}

#ljust(integer, padstr = ' ') ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.ljust(integer, padstr=' ')   => new_str
 *  
 *  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
 *  <code>String</code> of length <i>integer</i> with <i>str</i> left justified
 *  and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
 *     
 *     "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');
}

#lstripString

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

"  hello  ".lstrip   #=> "hello  "
"hello".lstrip       #=> "hello"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.lstrip   => new_str
 *  
 *  Returns a copy of <i>str</i> with leading whitespace removed. See also
 *  <code>String#rstrip</code> and <code>String#strip</code>.
 *     
 *     "  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!String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.lstrip!   => self or nil
 *  
 *  Removes leading whitespace from <i>str</i>, returning <code>nil</code> if no
 *  change was made. See also <code>String#rstrip!</code> and
 *  <code>String#strip!</code>.
 *     
 *     "  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?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.match(pattern)   => matchdata or nil
 *  
 *  Converts <i>pattern</i> to a <code>Regexp</code> (if it isn't already one),
 *  then invokes its <code>match</code> method on <i>str</i>.
 *     
 *     '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);
}

#succString #nextString

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         #=> "**+"

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.succ   => new_str
 *     str.next   => new_str
 *  
 *  Returns the successor to <i>str</i>. 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!String #next!String

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

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.succ!   => str
 *     str.next!   => str
 *  
 *  Equivalent to <code>String#succ</code>, 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;
}

#octInteger

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.oct   => integer
 *  
 *  Treats leading characters of <i>str</i> 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);
}

#partition(sep) ⇒ Array

Searches the string for sep and returns the part before it, the sep, and the part after it. If sep is not found, returns str and two empty strings. If no argument is given, Enumerable#partition is called.

"hello".partition("l")         #=> ["he", "l", "lo"]
"hello".partition("x")         #=> ["hello", "", ""]

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.partition(sep)              => [head, sep, tail]
 *  
 *  Searches the string for <i>sep</i> and returns the part before it,
 *  the <i>sep</i>, and the part after it.  If <i>sep</i> is not
 *  found, returns <i>str</i> and two empty strings.  If no argument
 *  is given, Enumerable#partition is called.
 *     
 *     "hello".partition("l")         #=> ["he", "l", "lo"]
 *     "hello".partition("x")         #=> ["hello", "", ""]
 */

static VALUE
rb_str_partition(argc, argv, str)
    int argc;
    VALUE *argv;
    VALUE str;
{
    VALUE sep;
    long pos;

    if (argc == 0) return rb_call_super(argc, argv);
    rb_scan_args(argc, argv, "1", &sep);
    if (TYPE(sep) != T_REGEXP) {
    VALUE tmp;

    tmp = rb_check_string_type(sep);
    if (NIL_P(tmp)) {
        rb_raise(rb_eTypeError, "type mismatch: %s given",
             rb_obj_classname(sep));
    }
        sep = get_arg_pat(tmp);
    }
    pos = rb_reg_search(sep, str, 0, 0);
    if (pos < 0) {
      failed:
    return rb_ary_new3(3, str, rb_str_new(0,0),rb_str_new(0,0));
    }
    sep = rb_str_subpat(str, sep, 0);
    if (pos == 0 && RSTRING(sep)->len == 0) goto failed;
    return rb_ary_new3(3, rb_str_substr(str, 0, pos),
                  sep,
                  rb_str_substr(str, pos+RSTRING(sep)->len,
                         RSTRING(str)->len-pos-RSTRING(sep)->len));
}

#replace(other_str) ⇒ String

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

s = "hello"         #=> "hello"
s.replace "world"   #=> "world"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.replace(other_str)   => str
 *  
 *  Replaces the contents and taintedness of <i>str</i> with the corresponding
 *  values in <i>other_str</i>.
 *     
 *     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;
}

#reverseString

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

"stressed".reverse   #=> "desserts"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.reverse   => new_str
 *  
 *  Returns a new string with the characters from <i>str</i> 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!String

Reverses str in place.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.reverse!   => str
 *  
 *  Reverses <i>str</i> 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? #rindex(fixnum[, fixnum]) ⇒ Fixnum? #rindex(regexp[, fixnum]) ⇒ Fixnum?

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

Overloads:

  • #rindex(substring[, fixnum]) ⇒ Fixnum?

    Returns:

  • #rindex(fixnum[, fixnum]) ⇒ Fixnum?

    Returns:

  • #rindex(regexp[, fixnum]) ⇒ Fixnum?

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.rindex(substring [, fixnum])   => fixnum or nil
 *     str.rindex(fixnum [, fixnum])   => fixnum or nil
 *     str.rindex(regexp [, fixnum])   => fixnum or nil
 *  
 *  Returns the index of the last occurrence of the given <i>substring</i>,
 *  character (<i>fixnum</i>), or pattern (<i>regexp</i>) in <i>str</i>. Returns
 *  <code>nil</code> 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;

      default: {
    VALUE tmp;

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

      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;
      }
    }
    return Qnil;
}

#rjust(integer, padstr = ' ') ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.rjust(integer, padstr=' ')   => new_str
 *  
 *  If <i>integer</i> is greater than the length of <i>str</i>, returns a new
 *  <code>String</code> of length <i>integer</i> with <i>str</i> right justified
 *  and padded with <i>padstr</i>; otherwise, returns <i>str</i>.
 *     
 *     "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');
}

#rpartition(sep) ⇒ Array

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

"hello".rpartition("l")         #=> ["hel", "l", "o"]
"hello".rpartition("x")         #=> ["", "", "hello"]

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.rpartition(sep)            => [head, sep, tail]
 *  
 *  Searches <i>sep</i> in the string from the end of the string, and
 *  returns the part before it, the <i>sep</i>, and the part after it.
 *  If <i>sep</i> is not found, returns two empty strings and
 *  <i>str</i>.
 *     
 *     "hello".rpartition("l")         #=> ["hel", "l", "o"]
 *     "hello".rpartition("x")         #=> ["", "", "hello"]
 */

static VALUE
rb_str_rpartition(str, sep)
    VALUE str;
    VALUE sep;
{
    long pos = RSTRING(str)->len;

    if (TYPE(sep) != T_REGEXP) {
    VALUE tmp;

    tmp = rb_check_string_type(sep);
    if (NIL_P(tmp)) {
        rb_raise(rb_eTypeError, "type mismatch: %s given",
             rb_obj_classname(sep));
    }
        sep = get_arg_pat(tmp);
    }
    pos = rb_reg_search(sep, str, pos, 1);
    if (pos < 0) {
    return rb_ary_new3(3, rb_str_new(0,0),rb_str_new(0,0), str);
    }
    sep = rb_reg_nth_match(0, rb_backref_get());
    return rb_ary_new3(3, rb_str_substr(str, 0, pos),
                  sep,
                  rb_str_substr(str, pos+RSTRING(sep)->len,
                         RSTRING(str)->len-pos-RSTRING(sep)->len));
}

#rstripString

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

"  hello  ".rstrip   #=> "  hello"
"hello".rstrip       #=> "hello"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.rstrip   => new_str
 *  
 *  Returns a copy of <i>str</i> with trailing whitespace removed. See also
 *  <code>String#lstrip</code> and <code>String#strip</code>.
 *     
 *     "  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!String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.rstrip!   => self or nil
 *  
 *  Removes trailing whitespace from <i>str</i>, returning <code>nil</code> if
 *  no change was made. See also <code>String#lstrip!</code> and
 *  <code>String#strip!</code>.
 *     
 *     "  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 #scan(pattern) {|match, ...| ... } ⇒ String

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

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.scan(pattern)                         => array
 *     str.scan(pattern) {|match, ...| block }   => str
 *  
 *  Both forms iterate through <i>str</i>, matching the pattern (which may be a
 *  <code>Regexp</code> or a <code>String</code>). 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, <code>$&</code>.  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"
 *     
 *  <em>produces:</em>
 *     
 *     <<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;
}

#lengthInteger

Returns the length of str.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.length   => integer
 *  
 *  Returns the length of <i>str</i>.
 */

static VALUE
rb_str_length(str)
    VALUE str;
{
    return LONG2NUM(RSTRING(str)->len);
}

#[](fixnum) ⇒ Fixnum? #[](fixnum, fixnum) ⇒ String? #[](range) ⇒ String? #[](regexp) ⇒ String? #[](regexp, fixnum) ⇒ String? #[](other_str) ⇒ String? #slice(fixnum) ⇒ Fixnum? #slice(fixnum, fixnum) ⇒ String? #slice(range) ⇒ String? #slice(regexp) ⇒ String? #slice(regexp, fixnum) ⇒ String? #slice(other_str) ⇒ String?

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

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str[fixnum]                 => fixnum or nil
 *     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
 *     str.slice(fixnum)           => fixnum or nil
 *     str.slice(fixnum, fixnum)   => new_str or nil
 *     str.slice(range)            => new_str or nil
 *     str.slice(regexp)           => new_str or nil
 *     str.slice(regexp, fixnum)   => new_str or nil
 *     str.slice(other_str)        => new_str or nil
 *  
 *  Element Reference---If passed a single <code>Fixnum</code>, returns the code
 *  of the character at that position. If passed two <code>Fixnum</code>
 *  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 <i>str</i>. Returns
 *  <code>nil</code> 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 <code>Regexp</code> is supplied, the matching portion of <i>str</i> is
 *  returned. If a numeric parameter follows the regular expression, that
 *  component of the <code>MatchData</code> is returned instead. If a
 *  <code>String</code> is given, that string is returned if it occurs in
 *  <i>str</i>. In both cases, <code>nil</code> 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? #slice!(fixnum, fixnum) ⇒ String? #slice!(range) ⇒ String? #slice!(regexp) ⇒ String? #slice!(other_str) ⇒ String?

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"

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.slice!(fixnum)           => fixnum or nil
 *     str.slice!(fixnum, fixnum)   => new_str or nil
 *     str.slice!(range)            => new_str or nil
 *     str.slice!(regexp)           => new_str or nil
 *     str.slice!(other_str)        => new_str or nil
 *  
 *  Deletes the specified portion from <i>str</i>, and returns the portion
 *  deleted. The forms that take a <code>Fixnum</code> will raise an
 *  <code>IndexError</code> if the value is out of range; the <code>Range</code>
 *  form will raise a <code>RangeError</code>, and the <code>Regexp</code> and
 *  <code>String</code> 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]) ⇒ Array

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", "", ""]

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.split(pattern=$;, [limit])   => anArray
 *  
 *  Divides <i>str</i> into substrings based on a delimiter, returning an array
 *  of these substrings.
 *     
 *  If <i>pattern</i> is a <code>String</code>, then its contents are used as
 *  the delimiter when splitting <i>str</i>. If <i>pattern</i> is a single
 *  space, <i>str</i> is split on whitespace, with leading whitespace and runs
 *  of contiguous whitespace characters ignored.
 *     
 *  If <i>pattern</i> is a <code>Regexp</code>, <i>str</i> is divided where the
 *  pattern matches. Whenever the pattern matches a zero-length string,
 *  <i>str</i> is split into individual characters.
 *     
 *  If <i>pattern</i> is omitted, the value of <code>$;</code> is used.  If
 *  <code>$;</code> is <code>nil</code> (which is the default), <i>str</i> is
 *  split on whitespace as if ` ' were specified.
 *     
 *  If the <i>limit</i> parameter is omitted, trailing null fields are
 *  suppressed. If <i>limit</i> is a positive number, at most that number of
 *  fields will be returned (if <i>limit</i> is <code>1</code>, 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]) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.squeeze([other_str]*)    => new_str
 *  
 *  Builds a set of characters from the <i>other_str</i> parameter(s) using the
 *  procedure described for <code>String#count</code>. 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]) ⇒ String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.squeeze!([other_str]*)   => str or nil
 *  
 *  Squeezes <i>str</i> in place, returning either <i>str</i>, or
 *  <code>nil</code> 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;
}

#start_with?([prefix]) ⇒ Boolean

Returns true if str starts with the prefix given.

Returns:

  • (Boolean)


# File 'string.c'

/*
 *  call-seq:
 *     str.start_with?([prefix]+)   => true or false
 *  
 *  Returns true if <i>str</i> starts with the prefix given.
 */

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

    for (i=0; i<argc; i++) {
    VALUE prefix = rb_check_string_type(argv[i]);
    if (NIL_P(prefix)) continue;
    if (RSTRING(str)->len < RSTRING(prefix)->len) continue;
        pat = get_arg_pat(prefix);
        if (rb_reg_search(pat, str, 0, 1) >= 0)
        return Qtrue;
    }
    return Qfalse;
}

#stripString

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

"    hello    ".strip   #=> "hello"
"\tgoodbye\r\n".strip   #=> "goodbye"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.strip   => new_str
 *  
 *  Returns a copy of <i>str</i> 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!String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.strip!   => str or nil
 *  
 *  Removes leading and trailing whitespace from <i>str</i>. Returns
 *  <code>nil</code> if <i>str</i> 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) ⇒ String #sub(pattern) {|match| ... } ⇒ String

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"

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.sub(pattern, replacement)         => new_str
 *     str.sub(pattern) {|match| block }     => new_str
 *  
 *  Returns a copy of <i>str</i> with the <em>first</em> occurrence of
 *  <i>pattern</i> replaced with either <i>replacement</i> or the value of the
 *  block. The <i>pattern</i> will typically be a <code>Regexp</code>; if it is
 *  a <code>String</code> then no regular expression metacharacters will be
 *  interpreted (that is <code>/\d/</code> will match a digit, but
 *  <code>'\d'</code> will match a backslash followed by a 'd').
 *     
 *  If the method call specifies <i>replacement</i>, special variables such as
 *  <code>$&</code> will not be useful, as substitution into the string occurs
 *  before the pattern match starts. However, the sequences <code>\1</code>,
 *  <code>\2</code>, etc., may be used.
 *     
 *  In the block form, the current match string is passed in as a parameter, and
 *  variables such as <code>$1</code>, <code>$2</code>, <code>$`</code>,
 *  <code>$&</code>, and <code>$'</code> 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) ⇒ String? #sub!(pattern) {|match| ... } ⇒ String?

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

Overloads:

  • #sub!(pattern, replacement) ⇒ String?

    Returns:

  • #sub!(pattern) {|match| ... } ⇒ String?

    Yields:

    Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.sub!(pattern, replacement)          => str or nil
 *     str.sub!(pattern) {|match| block }      => str or nil
 *  
 *  Performs the substitutions of <code>String#sub</code> in place,
 *  returning <i>str</i>, or <code>nil</code> 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;
}

#succString #nextString

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         #=> "**+"

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.succ   => new_str
 *     str.next   => new_str
 *  
 *  Returns the successor to <i>str</i>. 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!String #next!String

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

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.succ!   => str
 *     str.next!   => str
 *  
 *  Equivalent to <code>String#succ</code>, 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

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.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.sum(n=16)   => integer
 *  
 *  Returns a basic <em>n</em>-bit checksum of the characters in <i>str</i>,
 *  where <em>n</em> is the optional <code>Fixnum</code> parameter, defaulting
 *  to 16. The result is simply the sum of the binary value of each character in
 *  <i>str</i> modulo <code>2n - 1</code>. 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);
    }
}

#swapcaseString

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.swapcase   => new_str
 *  
 *  Returns a copy of <i>str</i> 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!String?

Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.swapcase!   => str or nil
 *  
 *  Equivalent to <code>String#swapcase</code>, but modifies the receiver in
 *  place, returning <i>str</i>, or <code>nil</code> 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_fFloat

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.to_f   => float
 *  
 *  Returns the result of interpreting leading characters in <i>str</i> 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 <i>str</i>,
 *  <code>0.0</code> 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

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

"12345".to_i             #=> 12345
"99 red balloons".to_i   #=> 99
"0a".to_i                #=> 0
"0a".to_i(16)            #=> 10
"hello".to_i             #=> 0
"1100101".to_i(2)        #=> 101
"1100101".to_i(8)        #=> 294977
"1100101".to_i(10)       #=> 1100101
"1100101".to_i(16)       #=> 17826049

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.to_i(base=10)   => integer
 *  
 *  Returns the result of interpreting leading characters in <i>str</i> as an
 *  integer base <i>base</i> (between 2 and 36). Extraneous characters past the
 *  end of a valid number are ignored. If there is not a valid number at the
 *  start of <i>str</i>, <code>0</code> 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_sString #to_strString

Returns the receiver.

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.to_s     => str
 *     str.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_sString #to_strString

Returns the receiver.

Overloads:



# File 'string.c'

/*
 *  call-seq:
 *     str.to_s     => str
 *     str.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;
}

#internObject #to_symObject

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"


# File 'string.c'

/*
 *  call-seq:
 *     str.intern   => symbol
 *     str.to_sym   => symbol
 *  
 *  Returns the <code>Symbol</code> corresponding to <i>str</i>, creating the
 *  symbol if it did not previously exist. See <code>Symbol#id2name</code>.
 *     
 *     "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
 *  <code>:xxx</code> 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) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.tr(from_str, to_str)   => new_str
 *  
 *  Returns a copy of <i>str</i> with the characters in <i>from_str</i> replaced
 *  by the corresponding characters in <i>to_str</i>. If <i>to_str</i> is
 *  shorter than <i>from_str</i>, it is padded with its last character. Both
 *  strings may use the c1--c2 notation to denote ranges of characters, and
 *  <i>from_str</i> may start with a <code>^</code>, 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) ⇒ String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.tr!(from_str, to_str)   => str or nil
 *  
 *  Translates <i>str</i> in place, using the same rules as
 *  <code>String#tr</code>. Returns <i>str</i>, or <code>nil</code> 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) ⇒ String

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.tr_s(from_str, to_str)   => new_str
 *  
 *  Processes a copy of <i>str</i> as described under <code>String#tr</code>,
 *  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) ⇒ String?

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

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.tr_s!(from_str, to_str)   => str or nil
 *  
 *  Performs <code>String#tr_s</code> processing on <i>str</i> in place,
 *  returning <i>str</i>, or <code>nil</code> 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) ⇒ Array

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
-------+---------+-----------------------------------------

Returns:



# File 'pack.c'

/*
 *  call-seq:
 *     str.unpack(format)   => anArray
 *  
 *  Decodes <i>str</i> (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 (``<code>*</code>'') will use up all
 *  remaining elements. The directives <code>sSiIlL</code> may each be
 *  followed by an underscore (``<code>_</code>'') 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 <code>Array#pack</code>.
 *     
 *     "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 const char hexdigits[] = "0123456789abcdef0123456789ABCDEFx";
    char *s, *send;
    char *p, *pend;
    VALUE ary;
    char type;
    long len, tmp_len;
    int star;
#ifdef NATINT_PACK
    int natint;         /* native integer */
#endif
    int signed_p, integer_size, bigendian_p;

    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 == '!') {
        static const char natstr[] = "sSiIlL";

        if (strchr(natstr, type)) {
#ifdef NATINT_PACK
        natint = 1;
#endif
        p++;
        }
        else {
        rb_raise(rb_eArgError, "'%c' allowed only after types %s", *p, natstr);
        }
    }
    if (p >= pend)
        len = 1;
    else if (*p == '*') {
        star = 1;
        len = send - s;
        p++;
    }
    else if (ISDIGIT(*p)) {
        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_SIZE(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_SIZE(sizeof(unsigned char));
        while (len-- > 0) {
        unsigned char c = *s++;
        rb_ary_push(ary, INT2FIX(c));
        }
        PACK_ITEM_ADJUST();
        break;

      case 's':
            signed_p = 1;
            integer_size = NATINT_LEN(short, 2);
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

      case 'S':
            signed_p = 0;
            integer_size = NATINT_LEN(short, 2);
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

      case 'i':
            signed_p = 1;
            integer_size = (int)sizeof(int);
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

      case 'I':
            signed_p = 0;
            integer_size = (int)sizeof(int);
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

      case 'l':
            signed_p = 1;
            integer_size = NATINT_LEN(long, 4);
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

          case 'L':
            signed_p = 0;
            integer_size = NATINT_LEN(long, 4);
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

          case 'q':
            signed_p = 1;
            integer_size = QUAD_SIZE;
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

          case 'Q':
            signed_p = 0;
            integer_size = QUAD_SIZE;
            bigendian_p = BIGENDIAN_P();
            goto unpack_integer;

          case 'n':
            signed_p = 0;
            integer_size = 2;
            bigendian_p = 1;
            goto unpack_integer;

          case 'N':
            signed_p = 0;
            integer_size = 4;
            bigendian_p = 1;
            goto unpack_integer;

          case 'v':
            signed_p = 0;
            integer_size = 2;
            bigendian_p = 0;
            goto unpack_integer;

          case 'V':
            signed_p = 0;
            integer_size = 4;
            bigendian_p = 0;
            goto unpack_integer;

          unpack_integer:
            switch (integer_size) {
#if defined(HAVE_INT16_T) && !defined(FORCE_BIG_PACK)
              case SIZEOF_INT16_T:
                if (signed_p) {
                    PACK_LENGTH_ADJUST_SIZE(sizeof(int16_t));
                    while (len-- > 0) {
                        union {
                            int16_t i;
                            char a[sizeof(int16_t)];
                        } v;
                        memcpy(v.a, s, sizeof(int16_t));
                        if (bigendian_p != BIGENDIAN_P()) v.i = swap16(v.i);
                        s += sizeof(int16_t);
                        rb_ary_push(ary, INT2FIX(v.i));
                    }
                    PACK_ITEM_ADJUST();
                }
                else {
                    PACK_LENGTH_ADJUST_SIZE(sizeof(uint16_t));
                    while (len-- > 0) {
                        union {
                            uint16_t i;
                            char a[sizeof(uint16_t)];
                        } v;
                        memcpy(v.a, s, sizeof(uint16_t));
                        if (bigendian_p != BIGENDIAN_P()) v.i = swap16(v.i);
                        s += sizeof(uint16_t);
                        rb_ary_push(ary, INT2FIX(v.i));
                    }
                    PACK_ITEM_ADJUST();
                }
                break;
#endif

#if defined(HAVE_INT32_T) && !defined(FORCE_BIG_PACK)
              case SIZEOF_INT32_T:
                if (signed_p) {
                    PACK_LENGTH_ADJUST_SIZE(sizeof(int32_t));
                    while (len-- > 0) {
                        union {
                            int32_t i;
                            char a[sizeof(int32_t)];
                        } v;
                        memcpy(v.a, s, sizeof(int32_t));
                        if (bigendian_p != BIGENDIAN_P()) v.i = swap32(v.i);
                        s += sizeof(int32_t);
                        rb_ary_push(ary, INT2NUM(v.i));
                    }
                    PACK_ITEM_ADJUST();
                }
                else {
                    PACK_LENGTH_ADJUST_SIZE(sizeof(uint32_t));
                    while (len-- > 0) {
                        union {
                            uint32_t i;
                            char a[sizeof(uint32_t)];
                        } v;
                        memcpy(v.a, s, sizeof(uint32_t));
                        if (bigendian_p != BIGENDIAN_P()) v.i = swap32(v.i);
                        s += sizeof(uint32_t);
                        rb_ary_push(ary, UINT2NUM(v.i));
                    }
                    PACK_ITEM_ADJUST();
                }
                break;
#endif

#if defined(HAVE_INT64_T) && !defined(FORCE_BIG_PACK)
              case SIZEOF_INT64_T:
                if (signed_p) {
                    PACK_LENGTH_ADJUST_SIZE(sizeof(int64_t));
                    while (len-- > 0) {
                        union {
                            int64_t i;
                            char a[sizeof(int64_t)];
                        } v;
                        memcpy(v.a, s, sizeof(int64_t));
                        if (bigendian_p != BIGENDIAN_P()) v.i = swap64(v.i);
                        s += sizeof(int64_t);
                        rb_ary_push(ary, INT64toNUM(v.i));
                    }
                    PACK_ITEM_ADJUST();
                }
                else {
                    PACK_LENGTH_ADJUST_SIZE(sizeof(uint64_t));
                    while (len-- > 0) {
                        union {
                            uint64_t i;
                            char a[sizeof(uint64_t)];
                        } v;
                        memcpy(v.a, s, sizeof(uint64_t));
                        if (bigendian_p != BIGENDIAN_P()) v.i = swap64(v.i);
                        s += sizeof(uint64_t);
                        rb_ary_push(ary, UINT64toNUM(v.i));
                    }
                    PACK_ITEM_ADJUST();
                }
                break;
#endif


              default:
                if (integer_size > MAX_INTEGER_PACK_SIZE)
                    rb_bug("unexpected intger size for pack: %d", integer_size);
                PACK_LENGTH_ADJUST_SIZE(integer_size);
                while (len-- > 0) {
                    union {
                        unsigned long i[(MAX_INTEGER_PACK_SIZE+SIZEOF_LONG)/SIZEOF_LONG];
                        char a[(MAX_INTEGER_PACK_SIZE+SIZEOF_LONG)/SIZEOF_LONG*SIZEOF_LONG];
                    } v;
                    int num_longs = (integer_size+SIZEOF_LONG)/SIZEOF_LONG;
                    int i;

                    if (signed_p && (signed char)s[bigendian_p ? 0 : (integer_size-1)] < 0)
                        memset(v.a, 0xff, sizeof(long)*num_longs);
                    else
                        memset(v.a, 0, sizeof(long)*num_longs);
                    if (bigendian_p)
                        memcpy(v.a + sizeof(long)*num_longs - integer_size, s, integer_size);
                    else
                        memcpy(v.a, s, integer_size);
                    if (bigendian_p) {
                        for (i = 0; i < num_longs/2; i++) {
                            unsigned long t = v.i[i];
                            v.i[i] = v.i[num_longs-1-i];
                            v.i[num_longs-1-i] = t;
                        }
                    }
                    if (bigendian_p != BIGENDIAN_P()) {
                        for (i = 0; i < num_longs; i++)
                            v.i[i] = swapl(v.i[i]);
                    }
                    s += integer_size;
                    rb_ary_push(ary, rb_big_unpack(v.i, num_longs));
                }
                PACK_ITEM_ADJUST();
                break;
            }
            break;

      case 'f':
      case 'F':
        PACK_LENGTH_ADJUST_SIZE(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_SIZE(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_SIZE(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_SIZE(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_SIZE(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_SIZE(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 *) <= (size_t)(send - s)) {
        VALUE tmp = Qnil;
        char *t;

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

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

            if (!(a = rb_str_associated(str))) {
            rb_raise(rb_eArgError, "no associated pointer");
            }
            p = RARRAY(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");
            }
        }
        rb_ary_push(ary, tmp);
        }
        break;

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

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

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

            if (!(a = rb_str_associated(str))) {
                rb_raise(rb_eArgError, "no associated pointer");
            }
            p = RARRAY(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");
            }
            }
            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;
}

#upcaseString

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"

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.upcase   => new_str
 *  
 *  Returns a copy of <i>str</i> 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!String?

Upcases the contents of str, returning nil if no changes were made.

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.upcase!   => str or nil
 *  
 *  Upcases the contents of <i>str</i>, returning <code>nil</code> 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, exclusive = false) {|s| ... } ⇒ String

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

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

produces:

a8 a9 b0 b1 b2 b3 b4 b5 b6
a8 a9 b0 b1 b2 b3 b4 b5 b6

Yields:

  • (s)

Returns:



# File 'string.c'

/*
 *  call-seq:
 *     str.upto(other_str, exclusive=false) {|s| block }   => str
 *  
 *  Iterates through successive values, starting at <i>str</i> and
 *  ending at <i>other_str</i> inclusive, passing each value in turn to
 *  the block. The <code>String#succ</code> method is used to generate
 *  each value.  If optional second argument exclusive is omitted or is <code>false</code>,
 *  the last value will be included; otherwise it will be excluded.
 *     
 *     "a8".upto("b6") {|s| print s, ' ' }
 *     for s in "a8".."b6"
 *       print s, ' '
 *     end
 *     
 *  <em>produces:</em>
 *     
 *     a8 a9 b0 b1 b2 b3 b4 b5 b6
 *     a8 a9 b0 b1 b2 b3 b4 b5 b6
 */

static VALUE
rb_str_upto_m(argc, argv, beg)
    int argc;
    VALUE *argv;
    VALUE beg;
{
    VALUE end, exclusive;

    rb_scan_args(argc, argv, "11", &end, &exclusive);

    return rb_str_upto(beg, end, RTEST(exclusive));
}