123456789_123456789_123456789_123456789_123456789_

Class: String

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Subclasses:
Super Chains via Extension / Inclusion / Inheritance
Instance Chain:
self, ::Comparable
Inherits: Object
Defined in: string.c,
complex.c,
encoding.c,
pack.rb,
rational.c,
symbol.c,
transcode.c

Overview

A String object has an arbitrary sequence of bytes, typically representing text or binary data. A String object may be created using .new or as literals.

String objects differ from ::Symbol objects in that ::Symbol objects are designed to be used as identifiers, instead of text or data.

You can create a String object explicitly with:

  • A string literal.

  • A heredoc literal.

You can convert certain objects to Strings with:

  • Method {Kernel.html#method-i-String }.

Some String methods modify self. Typically, a method whose name ends with ! modifies self and returns self; often a similarly named method (without the !) returns a new string.

In general, if there exist both bang and non-bang version of method, the bang! mutates and the non-bang! does not. However, a method without a bang can also mutate, such as #replace.

Substitution Methods

These methods perform substitutions:

  • #sub: One substitution (or none); returns a new string.

  • #sub!: One substitution (or none); returns self.

  • #gsub: Zero or more substitutions; returns a new string.

  • #gsub!: Zero or more substitutions; returns self.

Each of these methods takes:

  • A first argument, pattern (string or regexp), that specifies the substring(s) to be replaced.

  • Either of these:

    • A second argument, replacement (string or hash), that determines the replacing string.

    • A block that will determine the replacing string.

The examples in this section mostly use methods #sub and String#gsub; the principles illustrated apply to all four substitution methods.

Argument pattern

Argument pattern is commonly a regular expression:

s = 'hello'
s.sub(/[aeiou]/, '*')  # => "h*llo"
s.gsub(/[aeiou]/, '*') # => "h*ll*"
s.gsub(/[aeiou]/, '')  # => "hll"
s.sub(/ell/, 'al')     # => "halo"
s.gsub(/xyzzy/, '*')   # => "hello"
'THX1138'.gsub(/\d+/, '00') # => "THX00"

When pattern is a string, all its characters are treated as ordinary characters (not as regexp special characters):

'THX1138'.gsub('\d+', '00') # => "THX1138"

String replacement

If replacement is a string, that string will determine the replacing string that is to be substituted for the matched text.

Each of the examples above uses a simple string as the replacing string.

String replacement may contain back-references to the pattern’s captures:

  • \n (n a non-negative integer) refers to $n.

  • \k<name> refers to the named capture name.

See regexp.rdoc for details.

Note that within the string replacement, a character combination such as $& is treated as ordinary text, and not as a special match variable. However, you may refer to some special match variables using these combinations:

  • \& and \0 correspond to $&, which contains the complete matched text.

  • \' corresponds to $', which contains string after match.

  • \` corresponds to $`, which contains string before match.

  • + corresponds to $+, which contains last capture group.

See regexp.rdoc for details.

Note that \\ is interpreted as an escape, i.e., a single backslash.

Note also that a string literal consumes backslashes. See Literals for details about string literals.

A back-reference is typically preceded by an additional backslash. For example, if you want to write a back-reference \& in replacement with a double-quoted string literal, you need to write "..\\&..".

If you want to write a non-back-reference string \& in replacement, you need first to escape the backslash to prevent this method from interpreting it as a back-reference, and then you need to escape the backslashes again to prevent a string literal from consuming them: "..\\\\&..".

You may want to use the block form to avoid a lot of backslashes.

Hash replacement

If argument replacement is a hash, and pattern matches one of its keys, the replacing string is the value for that key:

h = {'foo' => 'bar', 'baz' => 'bat'}
'food'.sub('foo', h) # => "bard"

Note that a symbol key does not match:

h = {foo: 'bar', baz: 'bat'}
'food'.sub('foo', h) # => "d"

Block

In the block form, the current match string is passed to the block; the block’s return value becomes the replacing string:

 s = '@'
'1234'.gsub(/\d/) {|match| s.succ! } # => "ABCD"

Special match variables such as $1, $2, $`, $&, and $' are set appropriately.

What’s Here

First, what’s elsewhere. Class String:

  • Inherits from [class Object](Object.html#class-Object-label-What-27s+Here).

  • Includes [module Comparable](Comparable.html#module-Comparable-label-What-27s+Here).

Here, class String provides methods that are useful for:

Methods for Creating a String

  • ::new

    Returns a new string.

  • ::try_convert

    Returns a new string created from a given object.

Methods for a Frozen/Unfrozen String

  • #+string

    Returns a string that is not frozen:

    self, if not frozen; self.dup otherwise.
  • #-string

    Returns a string that is frozen:

    self, if already frozen; self.freeze otherwise.
  • #freeze

    Freezes self, if not already frozen; returns self.

Methods for Querying

Counts

  • #length, #size

    Returns the count of characters (not bytes).

  • #empty?

    Returns true if self.length is zero; false otherwise.

  • #bytesize

    Returns the count of bytes.

  • #count

    Returns the count of substrings matching given strings.

Substrings

  • #=~

    Returns the index of the first substring that matches a given ::Regexp or other object;

    returns nil if no match is found.
  • #index

    Returns the index of the first occurrence of a given substring; returns nil if none found.

  • #rindex

    Returns the index of the last occurrence of a given substring; returns nil if none found.

  • #include?

    Returns true if the string contains a given substring; false otherwise.

  • #match

    Returns a ::MatchData object if the string matches a given Regexp; nil otherwise.

  • #match?

    Returns true if the string matches a given Regexp; false otherwise.

  • #start_with?

    Returns true if the string begins with any of the given substrings.

  • #end_with?

    Returns true if the string ends with any of the given substrings.

Encodings

  • #encoding

    Returns the ::Encoding object that represents the encoding of the string.

  • #unicode_normalized?

    Returns true if the string is in Unicode normalized form; false otherwise.

  • #valid_encoding?

    Returns true if the string contains only characters that are valid for its encoding.

  • #ascii_only?

    Returns true if the string has only ASCII characters; false otherwise.

Other

  • #sum

    Returns a basic checksum for the string: the sum of each byte.

  • #hash

    Returns the integer hash code.

Methods for Comparing

  • {#==, #===}

    Returns true if a given other string has the same content as self.

  • #eql?

    Returns true if the content is the same as the given other string.

  • #<=>

    Returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than self.

  • #casecmp

    Ignoring case, returns -1, 0, or 1 as a given other string is smaller than, equal to, or larger than self.

  • #casecmp?

    Returns true if the string is equal to a given string after Unicode case folding; false otherwise.

Methods for Modifying a String

Each of these methods modifies self.

Insertion

  • #insert

    Returns self with a given string inserted at a given offset.

  • #<<

    Returns self concatenated with a given string or integer.

Substitution

  • #sub!

    Replaces the first substring that matches a given pattern with a given replacement string; returns self if any changes, nil otherwise.

  • #gsub!

    Replaces each substring that matches a given pattern with a given replacement string; returns self if any changes, nil otherwise.

  • #succ!, #next!

    Returns self modified to become its own successor.

  • #replace

    Returns self with its entire content replaced by a given string.

  • #reverse!

    Returns self with its characters in reverse order.

  • #setbyte

    Sets the byte at a given integer offset to a given value; returns the argument.

  • #tr!

    Replaces specified characters in self with specified replacement characters; returns self if any changes, nil otherwise.

  • #tr_s!

    Replaces specified characters in self with specified replacement characters, removing duplicates from the substrings that were modified; returns self if any changes, nil otherwise.

Casing

  • #capitalize!

    Upcases the initial character and downcases all others; returns self if any changes, nil otherwise.

  • #downcase!

    Downcases all characters; returns self if any changes, nil otherwise.

  • #upcase!

    Upcases all characters; returns self if any changes, nil otherwise.

  • #swapcase!

    Upcases each downcase character and downcases each upcase character; returns self if any changes, nil otherwise.

Encoding

  • #encode!

    Returns self with all characters transcoded from one given encoding into another.

  • #unicode_normalize!

    Unicode-normalizes self; returns self.

  • #scrub!

    Replaces each invalid byte with a given character; returns self.

  • #force_encoding

    Changes the encoding to a given encoding; returns self.

Deletion

  • #clear

    Removes all content, so that self is empty; returns self.

  • #slice!, #[]=

    Removes a substring determined by a given index, start/length, range, regexp, or substring.

  • #squeeze!

    Removes contiguous duplicate characters; returns self.

  • #delete!

    Removes characters as determined by the intersection of substring arguments.

  • #lstrip!

    Removes leading whitespace; returns self if any changes, nil otherwise.

  • #rstrip!

    Removes trailing whitespace; returns self if any changes, nil otherwise.

  • #strip!

    Removes leading and trailing whitespace; returns self if any changes, nil otherwise.

  • #chomp!

    Removes trailing record separator, if found; returns self if any changes, nil otherwise.

  • #chop!

    Removes trailing whitespace if found, otherwise removes the last character; returns self if any changes, nil otherwise.

Methods for Converting to New String

Each of these methods returns a new String based on self, often just a modified copy of self.

Extension

  • #*

    Returns the concatenation of multiple copies of self,

  • #+

    Returns the concatenation of self and a given other string.

  • #center

    Returns a copy of self centered between pad substring.

  • #concat

    Returns the concatenation of self with given other strings.

  • #prepend

    Returns the concatenation of a given other string with self.

  • #ljust

    Returns a copy of self of a given length, right-padded with a given other string.

  • #rjust

    Returns a copy of self of a given length, left-padded with a given other string.

Encoding

  • #b

    Returns a copy of self with ASCII-8BIT encoding.

  • #scrub

    Returns a copy of self with each invalid byte replaced with a given character.

  • #unicode_normalize

    Returns a copy of self with each character Unicode-normalized.

  • #encode

    Returns a copy of self with all characters transcoded from one given encoding into another.

Substitution

  • #dump

    Returns a copy of +self with all non-printing characters replaced by xHH notation and all special characters escaped.

  • #undump

    Returns a copy of +self with all \xNN notation replace by \uNNNN notation and all escaped characters unescaped.

  • #sub

    Returns a copy of self with the first substring matching a given pattern replaced with a given replacement string;.

  • #gsub

    Returns a copy of self with each substring that matches a given pattern replaced with a given replacement string.

  • #succ, #next

    Returns the string that is the successor to self.

  • #reverse

    Returns a copy of self with its characters in reverse order.

  • #tr

    Returns a copy of self with specified characters replaced with specified replacement characters.

  • #tr_s

    Returns a copy of self with specified characters replaced with specified replacement characters, removing duplicates from the substrings that were modified.

  • #%

    Returns the string resulting from formatting a given object into self

Casing

  • #capitalize

    Returns a copy of self with the first character upcased and all other characters downcased.

  • #downcase

    Returns a copy of self with all characters downcased.

  • #upcase

    Returns a copy of self with all characters upcased.

  • #swapcase

    Returns a copy of self with all upcase characters downcased and all downcase characters upcased.

Deletion

  • #delete

    Returns a copy of self with characters removed

  • #delete_prefix

    Returns a copy of self with a given prefix removed.

  • #delete_suffix

    Returns a copy of self with a given suffix removed.

  • #lstrip

    Returns a copy of self with leading whitespace removed.

  • #rstrip

    Returns a copy of self with trailing whitespace removed.

  • #strip

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

  • #chomp

    Returns a copy of self with a trailing record separator removed, if found.

  • #chop

    Returns a copy of self with trailing whitespace or the last character removed.

  • #squeeze

    Returns a copy of self with contiguous duplicate characters removed.

  • #[], #slice

    Returns a substring determined by a given index, start/length, or range, or string.

  • #byteslice

    Returns a substring determined by a given index, start/length, or range.

  • #chr

    Returns the first character.

Duplication

  • #to_s, $to_str

    If self is a subclass of String, returns self copied into a String;

    otherwise, returns self.

Methods for Converting to Non-String

Each of these methods converts the contents of self to a non-String.

Characters, Bytes, and Clusters

  • #bytes

    Returns an array of the bytes in self.

  • #chars

    Returns an array of the characters in self.

  • #codepoints

    Returns an array of the integer ordinals in self.

  • #getbyte

    Returns an integer byte as determined by a given index.

  • #grapheme_clusters

    Returns an array of the grapheme clusters in self.

Splitting

  • #lines

    Returns an array of the lines in self, as determined by a given record separator.

  • #partition

    Returns a 3-element array determined by the first substring that matches a given substring or regexp,

  • #rpartition

    Returns a 3-element array determined by the last substring that matches a given substring or regexp,

  • #split

    Returns an array of substrings determined by a given delimiter – regexp or string – or, if a block given, passes those substrings to the block.

Matching

  • #scan

    Returns an array of substrings matching a given regexp or string, or, if a block given, passes each matching substring to the block.

  • #unpack

    Returns an array of substrings extracted from self according to a given format.

  • #unpack1

    Returns the first substring extracted from self according to a given format.

Numerics

  • #hex

    Returns the integer value of the leading characters, interpreted as hexadecimal digits.

  • #oct

    Returns the integer value of the leading characters, interpreted as octal digits.

  • #ord

    Returns the integer ordinal of the first character in self.

  • #to_i

    Returns the integer value of leading characters, interpreted as an integer.

  • #to_f

    Returns the floating-point value of leading characters, interpreted as a floating-point number.

Strings and Symbols

  • #inspect

    Returns copy of self, enclosed in double-quotes, with special characters escaped.

  • #to_sym, #intern

    Returns the symbol corresponding to self.

Methods for Iterating

  • #each_byte

    Calls the given block with each successive byte in self.

  • #each_char

    Calls the given block with each successive character in self.

  • #each_codepoint

    Calls the given block with each successive integer codepoint in self.

  • #each_grapheme_cluster

    Calls the given block with each successive grapheme cluster in self.

  • #each_line

    Calls the given block with each successive line in self, as determined by a given record separator.

  • #upto

    Calls the given block with each string value returned by successive calls to #succ.

Class Method Summary

Instance Attribute Summary

Instance Method Summary

::Comparable - Included

#<

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value less than 0.

#<=

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value less than or equal to 0.

#==

Compares two objects based on the receiver’s #<=> method, returning true if it returns 0.

#>

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value greater than 0.

#>=

Compares two objects based on the receiver’s #<=> method, returning true if it returns a value greater than or equal to 0.

#between?

Returns false if obj #<=> min is less than zero or if obj #<=> max is greater than zero, true otherwise.

#clamp

In (min, max) form, returns min if obj #<=> min is less than zero, max if obj #<=> max is greater than zero, and obj otherwise.

Constructor Details

.new

[ GitHub ]

Class Method Details

.try_convert

[ GitHub ]

Instance Attribute Details

#ascii_only?Boolean (readonly)

Returns true for a string which has only ASCII characters.

"abc".force_encoding("UTF-8").ascii_only?          #=> true
"abc\u{6666}".force_encoding("UTF-8").ascii_only?  #=> false
[ GitHub ]

  
# File 'string.c', line 10794

static VALUE
rb_str_is_ascii_only_p(VALUE str)
{
    int cr = rb_enc_str_coderange(str);

    return RBOOL(cr == ENC_CODERANGE_7BIT);
}

#empty?Boolean (readonly)

[ GitHub ]

#valid_encoding?Boolean (readonly)

Returns true for a string which is encoded correctly.

"\xc2\xa1".force_encoding("UTF-8").valid_encoding?  #=> true
"\xc2".force_encoding("UTF-8").valid_encoding?      #=> false
"\x80".force_encoding("UTF-8").valid_encoding?      #=> false
[ GitHub ]

  
# File 'string.c', line 10776

static VALUE
rb_str_valid_encoding_p(VALUE str)
{
    int cr = rb_enc_str_coderange(str);

    return RBOOL(cr != ENC_CODERANGE_BROKEN);
}

Instance Method Details

#%

[ GitHub ]

#*

[ GitHub ]

#+

[ GitHub ]

#+@

[ GitHub ]

#-@

[ GitHub ]

#<<

[ GitHub ]

#<=>

[ GitHub ]

#==

[ GitHub ]

#===

[ GitHub ]

#=~

[ GitHub ]

#[](index) ⇒ String? #[](start, length) ⇒ String? #[](range) ⇒ String? #[](substring) ⇒ String?
Also known as: #slice

Returns the substring of self specified by the arguments.

When the single Integer argument #index is given, returns the 1-character substring found in self at offset #index:

'bar'[2] # => "r"

Counts backward from the end of self if #index is negative:

'foo'[-3] # => "f"

Returns nil if #index is out of range:

'foo'[3] # => nil
'foo'[-4] # => nil

When the two Integer arguments start and #length are given, returns the substring of the given #length found in self at offset start:

'foo'[0, 2] # => "fo"
'foo'[0, 0] # => ""

Counts backward from the end of self if start is negative:

'foo'[-2, 2] # => "oo"

Special case: returns a new empty String if start is equal to the length of self:

'foo'[3, 2] # => ""

Returns nil if start is out of range:

'foo'[4, 2] # => nil
'foo'[-4, 2] # => nil

Returns the trailing substring of self if #length is large:

'foo'[1, 50] # => "oo"

Returns nil if #length is negative:

'foo'[0, -1] # => nil

When the single Range argument range is given, derives start and #length values from the given range, and returns values as above:

  • 'foo'[0..1] is equivalent to 'foo'[0, 2].

  • 'foo'[0...1] is equivalent to 'foo'[0, 1].

When the Regexp argument regexp is given, and the capture argument is 0, returns the first matching substring found in self, or nil if none found:

'foo'[/o/] # => "o"
'foo'[/x/] # => nil
s = 'hello there'
s[/[aeiou](.)\1/] # => "ell"
s[/[aeiou](.)\1/, 0] # => "ell"

If argument capture is given and not 0, it should be either an Integer capture group index or a String or Symbol capture group name; the method call returns only the specified capture (see [Regexp Capturing](Regexp.html#class-Regexp-label-Capturing)):

s = 'hello there'
s[/[aeiou](.)\1/, 1] # => "l"
s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, "non_vowel"] # => "l"
s[/(?<vowel>[aeiou])(?<non_vowel>[^aeiou])/, :vowel] # => "e"

If an invalid capture group index is given, nil is returned. If an invalid capture group name is given, ::IndexError is raised.

When the single String argument substring is given, returns the substring from self if found, otherwise nil:

'foo'['oo'] # => "oo"
'foo'['xx'] # => nil

#slice is an alias for [].

[ GitHub ]

  
# File 'string.c', line 5053

static VALUE
rb_str_aref_m(int argc, VALUE *argv, VALUE str)
{
    if (argc == 2) {
	if (RB_TYPE_P(argv[0], T_REGEXP)) {
	    return rb_str_subpat(str, argv[0], argv[1]);
	}
	else {
	    long beg = NUM2LONG(argv[0]);
	    long len = NUM2LONG(argv[1]);
	    return rb_str_substr(str, beg, len);
	}
    }
    rb_check_arity(argc, 1, 2);
    return rb_str_aref(str, argv[0]);
}

#[]=(integer, new_str) #[]=(integer, integer, new_str) #[]=(range, aString) #[]=(regexp, new_str) #[]=(regexp, integer, new_str) #[]=(regexp, name, new_str) #[]=(other_str, new_str)

Element Assignment—Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as #[]. 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 ::Integer allows you to specify which portion of the match to replace (effectively using the ::MatchData indexing rules. The forms that take an ::Integer will raise an ::IndexError if the value is out of range; the ::Range form will raise a ::RangeError, and the ::Regexp and String will raise an ::IndexError on negative match.

[ GitHub ]

  
# File 'string.c', line 5282

static VALUE
rb_str_aset_m(int argc, VALUE *argv, VALUE str)
{
    if (argc == 3) {
	if (RB_TYPE_P(argv[0], T_REGEXP)) {
	    rb_str_subpat_set(str, argv[0], argv[1], argv[2]);
	}
	else {
	    rb_str_splice(str, NUM2LONG(argv[0]), NUM2LONG(argv[1]), argv[2]);
	}
	return argv[2];
    }
    rb_check_arity(argc, 2, 3);
    return rb_str_aset(str, argv[0], argv[1]);
}

#bString

Returns a copied string whose encoding is ASCII-8BIT.

[ GitHub ]

  
# File 'string.c', line 10750

static VALUE
rb_str_b(VALUE str)
{
    VALUE str2;
    if (FL_TEST(str, STR_NOEMBED)) {
        str2 = str_alloc_heap(rb_cString);
    }
    else {
        str2 = str_alloc_embed(rb_cString, RSTRING_EMBED_LEN(str) + TERM_LEN(str));
    }
    str_replace_shared_without_enc(str2, str);
    ENC_CODERANGE_CLEAR(str2);
    return str2;
}

#bytesArray

Returns an array of bytes in str. This is a shorthand for str.each_byte.to_a.

If a block is given, which is a deprecated form, works the same as #each_byte.

[ GitHub ]

  
# File 'string.c', line 8999

static VALUE
rb_str_bytes(VALUE str)
{
    VALUE ary = WANTARRAY("bytes", RSTRING_LEN(str));
    return rb_str_enumerate_bytes(str, ary);
}

#bytesize

[ GitHub ]

#byteslice(index, length = 1) ⇒ String? #byteslice(range) ⇒ String?

Returns a substring of self, or nil if the substring cannot be constructed.

With integer arguments #index and #length given, returns the substring beginning at the given #index of the given #length (if possible), or nil if #length is negative or #index falls outside of self:

s = '0123456789' # => "0123456789"
s.byteslice(2)   # => "2"
s.byteslice(200) # => nil
s.byteslice(4, 3)  # => "456"
s.byteslice(4, 30) # => "456789"
s.byteslice(4, -1) # => nil
s.byteslice(40, 2) # => nil

In either case above, counts backwards from the end of self if #index is negative:

s = '0123456789'   # => "0123456789"
s.byteslice(-4)    # => "6"
s.byteslice(-4, 3) # => "678"

With Range argument range given, returns byteslice(range.begin, range.size):

s = '0123456789'    # => "0123456789"
s.byteslice(4..6)   # => "456"
s.byteslice(-6..-4) # => "456"
s.byteslice(5..2)   # => "" # range.size is zero.
s.byteslice(40..42) # => nil

In all cases, a returned string has the same encoding as self:

s.encoding              # => #<Encoding:UTF-8>
s.byteslice(4).encoding # => #<Encoding:UTF-8>
[ GitHub ]

  
# File 'string.c', line 6108

static VALUE
rb_str_byteslice(int argc, VALUE *argv, VALUE str)
{
    if (argc == 2) {
	long beg = NUM2LONG(argv[0]);
	long end = NUM2LONG(argv[1]);
	return str_byte_substr(str, beg, end, TRUE);
    }
    rb_check_arity(argc, 1, 2);
    return str_byte_aref(str, argv[0]);
}

#capitalize(*options) ⇒ String

Returns a string containing the characters in self; the first character is upcased; the remaining characters are downcased:

s = 'hello World!' # => "hello World!"
s.capitalize       # => "Hello world!"

The casing may be affected by the given options; see Case Mapping.

Related: #capitalize!.

[ GitHub ]

  
# File 'string.c', line 7423

static VALUE
rb_str_capitalize(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_UPCASE | ONIGENC_CASE_TITLECASE;
    VALUE ret;

    flags = check_case_options(argc, argv, flags);
    enc = str_true_enc(str);
    if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return str;
    if (flags&ONIGENC_CASE_ASCII_ONLY) {
        ret = rb_str_new(0, RSTRING_LEN(str));
        rb_str_ascii_casemap(str, ret, &flags, enc);
    }
    else {
        ret = rb_str_casemap(str, &flags, enc);
    }
    return ret;
}

#capitalize!(*options) ⇒ self?

Upcases the first character in self; downcases the remaining characters; returns self if any changes were made, nil otherwise:

s = 'hello World!' # => "hello World!"
s.capitalize!      # => "Hello world!"
s                  # => "Hello world!"
s.capitalize!      # => nil

The casing may be affected by the given options; see Case Mapping.

Related: #capitalize.

[ GitHub ]

  
# File 'string.c', line 7385

static VALUE
rb_str_capitalize_bang(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_UPCASE | ONIGENC_CASE_TITLECASE;

    flags = check_case_options(argc, argv, flags);
    str_modify_keep_cr(str);
    enc = str_true_enc(str);
    if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil;
    if (flags&ONIGENC_CASE_ASCII_ONLY)
        rb_str_ascii_casemap(str, str, &flags, enc);
    else
	str_shared_replace(str, rb_str_casemap(str, &flags, enc));

    if (ONIGENC_CASE_MODIFIED&flags) return str;
    return Qnil;
}

#casecmp

[ GitHub ]

#casecmp?Boolean

[ GitHub ]

#center(width, padstr = ' ') ⇒ String

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

"hello".center(4)         #=> "hello"
"hello".center(20)        #=> "       hello        "
"hello".center(20, '123') #=> "1231231hello12312312"
[ GitHub ]

  
# File 'string.c', line 10354

static VALUE
rb_str_center(int argc, VALUE *argv, VALUE str)
{
    return rb_str_justify(argc, argv, str, 'c');
}

#charsArray

Returns an array of characters in str. This is a shorthand for str.each_char.to_a.

If a block is given, which is a deprecated form, works the same as #each_char.

[ GitHub ]

  
# File 'string.c', line 9077

static VALUE
rb_str_chars(VALUE str)
{
    VALUE ary = WANTARRAY("chars", rb_str_strlen(str));
    return rb_str_enumerate_chars(str, ary);
}

#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). If $/ is an empty string, it will remove all trailing newlines from the string.

"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"
"hello\r\n\r\n".chomp('')    #=> "hello"
"hello\r\n\r\r\n".chomp('')  #=> "hello\r\n\r"
[ GitHub ]

  
# File 'string.c', line 9558

static VALUE
rb_str_chomp(int argc, VALUE *argv, VALUE str)
{
    VALUE rs = chomp_rs(argc, argv);
    if (NIL_P(rs)) return str_duplicate(rb_cString, str);
    return rb_str_subseq(str, 0, chompped_length(str, rs));
}

#chomp!(separator = $/) ⇒ String?

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

[ GitHub ]

  
# File 'string.c', line 9524

static VALUE
rb_str_chomp_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE rs;
    str_modifiable(str);
    if (RSTRING_LEN(str) == 0) return Qnil;
    rs = chomp_rs(argc, argv);
    if (NIL_P(rs)) return Qnil;
    return rb_str_chomp_string(str, rs);
}

#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. #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       #=> ""
[ GitHub ]

  
# File 'string.c', line 9371

static VALUE
rb_str_chop(VALUE str)
{
    return rb_str_subseq(str, 0, chopped_length(str));
}

#chop!String?

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

[ GitHub ]

  
# File 'string.c', line 9335

static VALUE
rb_str_chop_bang(VALUE str)
{
    str_modify_keep_cr(str);
    if (RSTRING_LEN(str) > 0) {
	long len;
	len = chopped_length(str);
	STR_SET_LEN(str, len);
	TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str));
	if (ENC_CODERANGE(str) != ENC_CODERANGE_7BIT) {
	    ENC_CODERANGE_CLEAR(str);
	}
	return str;
    }
    return Qnil;
}

#chrString

Returns a string containing the first character of self:

s = 'foo' # => "foo"
s.chr     # => "f"
[ GitHub ]

  
# File 'string.c', line 5888

static VALUE
rb_str_chr(VALUE str)
{
    return rb_str_substr(str, 0, 1);
}

#clearself

Removes the contents of self:

s = 'foo' # => "foo"
s.clear   # => ""
[ GitHub ]

  
# File 'string.c', line 5863

static VALUE
rb_str_clear(VALUE str)
{
    str_discard(str);
    STR_SET_EMBED(str);
    STR_SET_EMBED_LEN(str, 0);
    RSTRING_PTR(str)[0] = 0;
    if (rb_enc_asciicompat(STR_ENC_GET(str)))
	ENC_CODERANGE_SET(str, ENC_CODERANGE_7BIT);
    else
	ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID);
    return str;
}

#codepointsArray

Returns an array of the ::Integer ordinals of the characters in str. This is a shorthand for str.each_codepoint.to_a.

If a block is given, which is a deprecated form, works the same as #each_codepoint.

[ GitHub ]

  
# File 'string.c', line 9152

static VALUE
rb_str_codepoints(VALUE str)
{
    VALUE ary = WANTARRAY("codepoints", rb_str_strlen(str));
    return rb_str_enumerate_codepoints(str, ary);
}

#concat

[ GitHub ]

#count([other_str]+) ⇒ Integer

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. The backslash character \ can be used to escape ^ or - and is otherwise ignored unless it appears at the end of a sequence or the end of a other_str.

a = "hello world"
a.count "lo"                   #=> 5
a.count "lo", "o"              #=> 2
a.count "hello", "^l"          #=> 4
a.count "ej-m"                 #=> 4

"hello^world".count "\\^aeiou" #=> 4
"hello-world".count "a\\-eo"   #=> 4

c = "hello world\\r\\n"
c.count "\\"                   #=> 2
c.count "\\A"                  #=> 0
c.count "X-\\w"                #=> 3
[ GitHub ]

  
# File 'string.c', line 8244

static VALUE
rb_str_count(int argc, VALUE *argv, VALUE str)
{
    char table[TR_TABLE_SIZE];
    rb_encoding *enc = 0;
    VALUE del = 0, nodel = 0, tstr;
    char *s, *send;
    int i;
    int ascompat;
    size_t n = 0;

    rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);

    tstr = argv[0];
    StringValue(tstr);
    enc = rb_enc_check(str, tstr);
    if (argc == 1) {
	const char *ptstr;
	if (RSTRING_LEN(tstr) == 1 && rb_enc_asciicompat(enc) &&
	    (ptstr = RSTRING_PTR(tstr),
	     ONIGENC_IS_ALLOWED_REVERSE_MATCH(enc, (const unsigned char *)ptstr, (const unsigned char *)ptstr+1)) &&
	    !is_broken_string(str)) {
	    int clen;
	    unsigned char c = rb_enc_codepoint_len(ptstr, ptstr+1, &clen, enc);

	    s = RSTRING_PTR(str);
	    if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0);
	    send = RSTRING_END(str);
	    while (s < send) {
		if (*(unsigned char*)s++ == c) n++;
	    }
	    return SIZET2NUM(n);
	}
    }

    tr_setup_table(tstr, table, TRUE, &del, &nodel, enc);
    for (i=1; i<argc; i++) {
	tstr = argv[i];
	StringValue(tstr);
	enc = rb_enc_check(str, tstr);
	tr_setup_table(tstr, table, FALSE, &del, &nodel, enc);
    }

    s = RSTRING_PTR(str);
    if (!s || RSTRING_LEN(str) == 0) return INT2FIX(0);
    send = RSTRING_END(str);
    ascompat = rb_enc_asciicompat(enc);
    while (s < send) {
	unsigned int c;

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

    return SIZET2NUM(n);
}

#crypt(salt_str) ⇒ String

Returns the string generated by calling crypt(3) standard library function with str and salt_str, in this order, as its arguments. Please do not use this method any longer. It is legacy; provided only for backward compatibility with ruby scripts in earlier days. It is bad to use in contemporary programs for several reasons:

  • Behaviour of C’s crypt(3) depends on the OS it is run. The generated string lacks data portability.

  • On some OSes such as Mac OS, crypt(3) never fails (i.e. silently ends up in unexpected results).

  • On some OSes such as Mac OS, crypt(3) is not thread safe.

  • So-called “traditional” usage of crypt(3) is very very very weak. According to its manpage, Linux’s traditional crypt(3) output has only 2**56 variations; too easy to brute force today. And this is the default behaviour.

  • In order to make things robust some OSes implement so-called “modular” usage. To go through, you have to do a complex build-up of the salt_str parameter, by hand. Failure in generation of a proper salt string tends not to yield any errors; typos in parameters are normally not detectable.

    • For instance, in the following example, the second invocation of String#crypt is wrong; it has a typo in “round=” (lacks “s”). However the call does not fail and something unexpected is generated.

      "foo".crypt("$5$rounds=1000$salt$") # OK, proper usage
      "foo".crypt("$5$round=1000$salt$")  # Typo not detected
  • Even in the “modular” mode, some hash functions are considered archaic and no longer recommended at all; for instance module $1$ is officially abandoned by its author: see

phk.freebsd.dk/sagas/md5crypt_eol/ . For another

instance module <code>$3$</code> is considered completely
broken: see the manpage of FreeBSD.
  • On some OS such as Mac OS, there is no modular mode. Yet, as written above, crypt(3) on Mac OS never fails. This means even if you build up a proper salt string it generates a traditional DES hash anyways, and there is no way for you to be aware of.

    "foo".crypt("$5$rounds=1000$salt$") # => "$5fNPQMxC5j6."

If for some reason you cannot migrate to other secure contemporary password hashing algorithms, install the string-crypt gem and require 'string/crypt' to continue using it.

[ GitHub ]

  
# File 'string.c', line 10070

static VALUE
rb_str_crypt(VALUE str, VALUE salt)
{
#ifdef HAVE_CRYPT_R
    VALUE databuf;
    struct crypt_data *data;
#   define CRYPT_END() ALLOCV_END(databuf)
#else
    extern char *crypt(const char *, const char *);
#   define CRYPT_END() rb_nativethread_lock_unlock(&crypt_mutex.lock)
#endif
    VALUE result;
    const char *s, *saltp;
    char *res;
#ifdef BROKEN_CRYPT
    char salt_8bit_clean[3];
#endif

    StringValue(salt);
    mustnot_wchar(str);
    mustnot_wchar(salt);
    s = StringValueCStr(str);
    saltp = RSTRING_PTR(salt);
    if (RSTRING_LEN(salt) < 2 || !saltp[0] || !saltp[1]) {
	rb_raise(rb_eArgError, "salt too short (need >=2 bytes)");
    }

#ifdef BROKEN_CRYPT
    if (!ISASCII((unsigned char)saltp[0]) || !ISASCII((unsigned char)saltp[1])) {
	salt_8bit_clean[0] = saltp[0] & 0x7f;
	salt_8bit_clean[1] = saltp[1] & 0x7f;
	salt_8bit_clean[2] = '\0';
	saltp = salt_8bit_clean;
    }
#endif
#ifdef HAVE_CRYPT_R
    data = ALLOCV(databuf, sizeof(struct crypt_data));
# ifdef HAVE_STRUCT_CRYPT_DATA_INITIALIZED
    data->initialized = 0;
# endif
    res = crypt_r(s, saltp, data);
#else
    crypt_mutex_initialize();
    rb_nativethread_lock_lock(&crypt_mutex.lock);
    res = crypt(s, saltp);
#endif
    if (!res) {
	int err = errno;
	CRYPT_END();
	rb_syserr_fail(err, "crypt");
    }
    result = rb_str_new_cstr(res);
    CRYPT_END();
    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 #count.

"hello".delete "l","lo"        #=> "heo"
"hello".delete "lo"            #=> "he"
"hello".delete "aeiou", "^e"   #=> "hell"
"hello".delete "ej-m"          #=> "ho"
[ GitHub ]

  
# File 'string.c', line 8063

static VALUE
rb_str_delete(int argc, VALUE *argv, VALUE str)
{
    str = str_duplicate(rb_cString, 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.

[ GitHub ]

  
# File 'string.c', line 7987

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

    if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return Qnil;
    rb_check_arity(argc, 1, UNLIMITED_ARGUMENTS);
    for (i=0; i<argc; i++) {
	VALUE s = argv[i];

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

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

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

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

    if (modify) return str;
    return Qnil;
}

#delete_prefix(prefix) ⇒ String

Returns a copy of str with leading prefix deleted.

"hello".delete_prefix("hel") #=> "lo"
"hello".delete_prefix("llo") #=> "hello"
[ GitHub ]

  
# File 'string.c', line 10605

static VALUE
rb_str_delete_prefix(VALUE str, VALUE prefix)
{
    long prefixlen;

    prefixlen = deleted_prefix_length(str, prefix);
    if (prefixlen <= 0) return str_duplicate(rb_cString, str);

    return rb_str_subseq(str, prefixlen, RSTRING_LEN(str) - prefixlen);
}

#delete_prefix!(prefix) ⇒ self?

Deletes leading prefix from str, returning nil if no change was made.

"hello".delete_prefix!("hel") #=> "lo"
"hello".delete_prefix!("llo") #=> nil
[ GitHub ]

  
# File 'string.c', line 10583

static VALUE
rb_str_delete_prefix_bang(VALUE str, VALUE prefix)
{
    long prefixlen;
    str_modify_keep_cr(str);

    prefixlen = deleted_prefix_length(str, prefix);
    if (prefixlen <= 0) return Qnil;

    return rb_str_drop_bytes(str, prefixlen);
}

#delete_suffix(suffix) ⇒ String

Returns a copy of str with trailing suffix deleted.

"hello".delete_suffix("llo") #=> "he"
"hello".delete_suffix("hel") #=> "hello"
[ GitHub ]

  
# File 'string.c', line 10691

static VALUE
rb_str_delete_suffix(VALUE str, VALUE suffix)
{
    long suffixlen;

    suffixlen = deleted_suffix_length(str, suffix);
    if (suffixlen <= 0) return str_duplicate(rb_cString, str);

    return rb_str_subseq(str, 0, RSTRING_LEN(str) - suffixlen);
}

#delete_suffix!(suffix) ⇒ self?

Deletes trailing suffix from str, returning nil if no change was made.

"hello".delete_suffix!("llo") #=> "he"
"hello".delete_suffix!("hel") #=> nil
[ GitHub ]

  
# File 'string.c', line 10661

static VALUE
rb_str_delete_suffix_bang(VALUE str, VALUE suffix)
{
    long olen, suffixlen, len;
    str_modifiable(str);

    suffixlen = deleted_suffix_length(str, suffix);
    if (suffixlen <= 0) return Qnil;

    olen = RSTRING_LEN(str);
    str_modify_keep_cr(str);
    len = olen - suffixlen;
    STR_SET_LEN(str, len);
    TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str));
    if (ENC_CODERANGE(str) != ENC_CODERANGE_7BIT) {
	ENC_CODERANGE_CLEAR(str);
    }
    return str;
}

#downcase(*options) ⇒ String

Returns a string containing the downcased characters in self:

s = 'Hello World!' # => "Hello World!"
s.downcase         # => "hello world!"

The casing may be affected by the given options; see Case Mapping.

Related: #downcase!, #upcase, #upcase!.

[ GitHub ]

  
# File 'string.c', line 7339

static VALUE
rb_str_downcase(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_DOWNCASE;
    VALUE ret;

    flags = check_case_options(argc, argv, flags);
    enc = str_true_enc(str);
    if (case_option_single_p(flags, enc, str)) {
        ret = rb_str_new(RSTRING_PTR(str), RSTRING_LEN(str));
        str_enc_copy(ret, str);
        downcase_single(ret);
    }
    else if (flags&ONIGENC_CASE_ASCII_ONLY) {
        ret = rb_str_new(0, RSTRING_LEN(str));
        rb_str_ascii_casemap(str, ret, &flags, enc);
    }
    else {
        ret = rb_str_casemap(str, &flags, enc);
    }

    return ret;
}

#downcase!(*options) ⇒ self?

Downcases the characters in self; returns self if any changes were made, nil otherwise:

s = 'Hello World!' # => "Hello World!"
s.downcase!        # => "hello world!"
s                  # => "hello world!"
s.downcase!        # => nil

The casing may be affected by the given options; see Case Mapping.

Related: #downcase, #upcase, #upcase!.

[ GitHub ]

  
# File 'string.c', line 7300

static VALUE
rb_str_downcase_bang(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_DOWNCASE;

    flags = check_case_options(argc, argv, flags);
    str_modify_keep_cr(str);
    enc = str_true_enc(str);
    if (case_option_single_p(flags, enc, str)) {
        if (downcase_single(str))
            flags |= ONIGENC_CASE_MODIFIED;
    }
    else if (flags&ONIGENC_CASE_ASCII_ONLY)
        rb_str_ascii_casemap(str, str, &flags, enc);
    else
	str_shared_replace(str, rb_str_casemap(str, &flags, enc));

    if (ONIGENC_CASE_MODIFIED&flags) return str;
    return Qnil;
}

#dumpString

Returns a printable version of self, enclosed in double-quotes, with special characters escaped, and with non-printing characters replaced by hexadecimal notation:

"hello \n ''".dump    # => "\"hello \\n ''\""
"\f\x00\xff\\\"".dump # => "\"\\f\\x00\\xFF\\\\\\\"\""

Related: #undump (inverse of dump).

[ GitHub ]

  
# File 'string.c', line 6567

VALUE
rb_str_dump(VALUE str)
{
    int encidx = rb_enc_get_index(str);
    rb_encoding *enc = rb_enc_from_index(encidx);
    long len;
    const char *p, *pend;
    char *q, *qend;
    VALUE result;
    int u8 = (encidx == rb_utf8_encindex());
    static const char nonascii_suffix[] = ".dup.force_encoding(\"%s\")";

    len = 2;			/* "" */
    if (!rb_enc_asciicompat(enc)) {
	len += strlen(nonascii_suffix) - rb_strlen_lit("%s");
	len += strlen(enc->name);
    }

    p = RSTRING_PTR(str); pend = p + RSTRING_LEN(str);
    while (p < pend) {
	int clen;
	unsigned char c = *p++;

	switch (c) {
	  case '"':  case '\\':
	  case '\n': case '\r':
	  case '\t': case '\f':
	  case '\013': case '\010': case '\007': case '\033':
	    clen = 2;
	    break;

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

	  default:
	    if (ISPRINT(c)) {
		clen = 1;
	    }
	    else {
		if (u8 && c > 0x7F) {	/* \u notation */
		    int n = rb_enc_precise_mbclen(p-1, pend, enc);
		    if (MBCLEN_CHARFOUND_P(n)) {
			unsigned int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc);
			if (cc <= 0xFFFF)
			    clen = 6;  /* \uXXXX */
			else if (cc <= 0xFFFFF)
			    clen = 9;  /* \u{XXXXX} */
			else
			    clen = 10; /* \u{XXXXXX} */
			p += MBCLEN_CHARFOUND_LEN(n)-1;
			break;
		    }
		}
		clen = 4;	/* \xNN */
	    }
	    break;
	}

	if (clen > LONG_MAX - len) {
	    rb_raise(rb_eRuntimeError, "string size too big");
	}
	len += clen;
    }

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

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

	if (c == '"' || c == '\\') {
	    *q++ = '\\';
	    *q++ = c;
	}
	else if (c == '#') {
	    if (IS_EVSTR(p, pend)) *q++ = '\\';
	    *q++ = '#';
	}
	else if (c == '\n') {
	    *q++ = '\\';
	    *q++ = 'n';
	}
	else if (c == '\r') {
	    *q++ = '\\';
	    *q++ = 'r';
	}
	else if (c == '\t') {
	    *q++ = '\\';
	    *q++ = 't';
	}
	else if (c == '\f') {
	    *q++ = '\\';
	    *q++ = 'f';
	}
	else if (c == '\013') {
	    *q++ = '\\';
	    *q++ = 'v';
	}
	else if (c == '\010') {
	    *q++ = '\\';
	    *q++ = 'b';
	}
	else if (c == '\007') {
	    *q++ = '\\';
	    *q++ = 'a';
	}
	else if (c == '\033') {
	    *q++ = '\\';
	    *q++ = 'e';
	}
	else if (ISPRINT(c)) {
	    *q++ = c;
	}
	else {
	    *q++ = '\\';
	    if (u8) {
		int n = rb_enc_precise_mbclen(p-1, pend, enc) - 1;
		if (MBCLEN_CHARFOUND_P(n)) {
		    int cc = rb_enc_mbc_to_codepoint(p-1, pend, enc);
		    p += n;
		    if (cc <= 0xFFFF)
			snprintf(q, qend-q, "u%04X", cc);    /* \uXXXX */
		    else
			snprintf(q, qend-q, "u{%X}", cc);  /* \u{XXXXX} or \u{XXXXXX} */
		    q += strlen(q);
		    continue;
		}
	    }
	    snprintf(q, qend-q, "x%02X", c);
	    q += 3;
	}
    }
    *q++ = '"';
    *q = '\0';
    if (!rb_enc_asciicompat(enc)) {
	snprintf(q, qend-q, nonascii_suffix, enc->name);
	encidx = rb_ascii8bit_encindex();
    }
    /* result from dump is ASCII */
    rb_enc_associate_index(result, encidx);
    ENC_CODERANGE_SET(result, ENC_CODERANGE_7BIT);
    return result;
}

#each_byte {|integer| ... } ⇒ String #each_byteEnumerator

Passes each byte in str to the given block, or returns an enumerator if no block is given.

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

produces:

104 101 108 108 111
[ GitHub ]

  
# File 'string.c', line 8981

static VALUE
rb_str_each_byte(VALUE str)
{
    RETURN_SIZED_ENUMERATOR(str, 0, 0, rb_str_each_byte_size);
    return rb_str_enumerate_bytes(str, 0);
}

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

Passes each character in str to the given block, or returns an enumerator if no block is given.

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

produces:

h e l l o
[ GitHub ]

  
# File 'string.c', line 9059

static VALUE
rb_str_each_char(VALUE str)
{
    RETURN_SIZED_ENUMERATOR(str, 0, 0, rb_str_each_char_size);
    return rb_str_enumerate_chars(str, 0);
}

#each_codepoint {|integer| ... } ⇒ String #each_codepointEnumerator

Passes the ::Integer ordinal of each character in str, also known as a codepoint when applied to Unicode strings to the given block. For encodings other than UTF-8/UTF-16(BE|LE)/UTF-32(BE|LE), values are directly derived from the binary representation of each character.

If no block is given, an enumerator is returned instead.

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

produces:

104 101 108 108 111 1593
[ GitHub ]

  
# File 'string.c', line 9133

static VALUE
rb_str_each_codepoint(VALUE str)
{
    RETURN_SIZED_ENUMERATOR(str, 0, 0, rb_str_each_char_size);
    return rb_str_enumerate_codepoints(str, 0);
}

#each_grapheme_cluster {|cstr| ... } ⇒ String #each_grapheme_clusterEnumerator

Passes each grapheme cluster in str to the given block, or returns an enumerator if no block is given. Unlike #each_char, this enumerates by grapheme clusters defined by Unicode Standard Annex #29 unicode.org/reports/tr29/

"a\u0300".each_char.to_a.size #=> 2
"a\u0300".each_grapheme_cluster.to_a.size #=> 1
[ GitHub ]

  
# File 'string.c', line 9283

static VALUE
rb_str_each_grapheme_cluster(VALUE str)
{
    RETURN_SIZED_ENUMERATOR(str, 0, 0, rb_str_each_grapheme_cluster_size);
    return rb_str_enumerate_grapheme_clusters(str, 0);
}

#each_line(separator = $/, chomp: false) {|substr| ... } ⇒ String #each_line(separator = $/, chomp: false) ⇒ Enumerator

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.

If #chomp is true, separator will be removed from the end of each line.

If no block is given, an enumerator is returned instead.

"hello\nworld".each_line {|s| p s}
# prints:
#   "hello\n"
#   "world"

"hello\nworld".each_line('l') {|s| p s}
# prints:
#   "hel"
#   "l"
#   "o\nworl"
#   "d"

"hello\n\n\nworld".each_line('') {|s| p s}
# prints
#   "hello\n\n"
#   "world"

"hello\nworld".each_line(chomp: true) {|s| p s}
# prints:
#   "hello"
#   "world"

"hello\nworld".each_line('l', chomp: true) {|s| p s}
# prints:
#   "he"
#   ""
#   "o\nwor"
#   "d"
[ GitHub ]

  
# File 'string.c', line 8913

static VALUE
rb_str_each_line(int argc, VALUE *argv, VALUE str)
{
    RETURN_SIZED_ENUMERATOR(str, argc, argv, 0);
    return rb_str_enumerate_lines(argc, argv, str, 0);
}

#encode(encoding, **options) ⇒ String #encode(dst_encoding, src_encoding, **options) ⇒ String #encode(**options) ⇒ String

The first form returns a copy of str transcoded to encoding #encoding. The second form returns a copy of str transcoded from src_encoding to dst_encoding. The last form returns a copy of str transcoded to Encoding.default_internal.

By default, the first and second form raise ::Encoding::UndefinedConversionError for characters that are undefined in the destination encoding, and ::Encoding::InvalidByteSequenceError for invalid byte sequences in the source encoding. The last form by default does not raise exceptions but uses replacement strings.

The options keyword arguments give details for conversion. The arguments are:

:invalid

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

:undef

If the value is :replace, #encode replaces characters which are undefined in the destination encoding with the replacement character. The default is to raise the Encoding::UndefinedConversionError.

:replace

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

:fallback

Sets the replacement string by the given object for undefined character. The object should be a Hash, a Proc, a Method, or an object which has [] method. Its key is an undefined character encoded in the source encoding of current transcoder. Its value can be any encoding until it can be converted into the destination encoding of the transcoder.

:xml

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

:cr_newline

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

:crlf_newline

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

:universal_newline

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

[ GitHub ]

  
# File 'transcode.c', line 2920

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

#encode!(encoding, **options) ⇒ String #encode!(dst_encoding, src_encoding, **options) ⇒ String

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

[ GitHub ]

  
# File 'transcode.c', line 2842

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

    rb_check_frozen(str);

    newstr = str;
    encidx = str_transcode(argc, argv, &newstr);

    if (encidx < 0) return str;
    if (newstr == str) {
	rb_enc_associate_index(str, encidx);
	return str;
    }
    rb_str_shared_replace(str, newstr);
    return str_encode_associate(str, encidx);
}

#encodingEncoding

Alias for Regexp#encoding.

#end_with?([suffixes]+) ⇒ Boolean

Returns true if str ends with one of the suffixes given.

"hello".end_with?("ello")               #=> true

# returns true if one of the suffixes matches.
"hello".end_with?("heaven", "ello")     #=> true
"hello".end_with?("heaven", "paradise") #=> false
[ GitHub ]

  
# File 'string.c', line 10516

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

    for (i=0; i<argc; i++) {
	VALUE tmp = argv[i];
	long slen, tlen;
	StringValue(tmp);
	enc = rb_enc_check(str, tmp);
	if ((tlen = RSTRING_LEN(tmp)) == 0) return Qtrue;
	if ((slen = RSTRING_LEN(str)) < tlen) continue;
	p = RSTRING_PTR(str);
        e = p + slen;
	s = e - tlen;
	if (rb_enc_left_char_head(p, s, e, enc) != s)
	    continue;
	if (memcmp(s, RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0)
	    return Qtrue;
    }
    return Qfalse;
}

#eql?Boolean

[ GitHub ]

#force_encoding(encoding) ⇒ String

Changes the encoding to #encoding and returns self.

[ GitHub ]

  
# File 'string.c', line 10734

static VALUE
rb_str_force_encoding(VALUE str, VALUE enc)
{
    str_modifiable(str);
    rb_enc_associate(str, rb_to_encoding(enc));
    ENC_CODERANGE_CLEAR(str);
    return str;
}

#freeze

[ GitHub ]

#getbyte(index) ⇒ Integer

Returns the byte at zero-based #index as an integer:

s = 'abcde'  # => "abcde"
s.getbyte(0) # => 97
s.getbyte(1) # => 98

Related: #setbyte.

[ GitHub ]

  
# File 'string.c', line 5906

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

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

    return INT2FIX((unsigned char)RSTRING_PTR(str)[pos]);
}

#grapheme_clustersArray

Returns an array of grapheme clusters in str. This is a shorthand for str.each_grapheme_cluster.to_a.

If a block is given, which is a deprecated form, works the same as #each_grapheme_cluster.

[ GitHub ]

  
# File 'string.c', line 9301

static VALUE
rb_str_grapheme_clusters(VALUE str)
{
    VALUE ary = WANTARRAY("grapheme_clusters", rb_str_strlen(str));
    return rb_str_enumerate_grapheme_clusters(str, ary);
}

#gsub(pattern, replacement) ⇒ String #gsub(pattern) {|match| ... } ⇒ String #gsub(pattern) ⇒ Enumerator

Returns a copy of self with all occurrences of the given pattern replaced.

See Substitution Methods.

Returns an ::Enumerator if no replacement and no block given.

Related: #sub, #sub!, #gsub!.

[ GitHub ]

  
# File 'string.c', line 5823

static VALUE
rb_str_gsub(int argc, VALUE *argv, VALUE str)
{
    return str_gsub(argc, argv, str, 0);
}

#gsub!(pattern, replacement) ⇒ self? #gsub!(pattern) {|match| ... } ⇒ self? #gsub!(pattern) ⇒ Enumerator

Performs the specified substring replacement(s) on self; returns self if any replacement occurred, nil otherwise.

See Substitution Methods.

Returns an ::Enumerator if no replacement and no block given.

Related: #sub, #gsub, #sub!.

[ GitHub ]

  
# File 'string.c', line 5799

static VALUE
rb_str_gsub_bang(int argc, VALUE *argv, VALUE str)
{
    str_modify_keep_cr(str);
    return str_gsub(argc, argv, str, 1);
}

#hash

[ GitHub ]

#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
[ GitHub ]

  
# File 'string.c', line 9943

static VALUE
rb_str_hex(VALUE str)
{
    return rb_str_to_inum(str, 16, FALSE);
}

#include?(other_string) ⇒ Boolean

Returns true if self contains other_string, false otherwise:

s = 'foo'
s.include?('f')    # => true
s.include?('fo')   # => true
s.include?('food') # => false
[ GitHub ]

  
# File 'string.c', line 6233

static VALUE
rb_str_include(VALUE str, VALUE arg)
{
    long i;

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

    return RBOOL(i != -1);
}

#index

[ GitHub ]

#replace(other_string) ⇒ self #initialize_copy(other_string) ⇒ self

Alias for #replace.

#insert(index, other_string) ⇒ self

Inserts the given other_string into self; returns self.

If the Integer #index is positive, inserts other_string at offset #index:

'foo'.insert(1, 'bar') # => "fbaroo"

If the Integer #index is negative, counts backward from the end of self and inserts other_string at offset #index1</tt> (that is, after self[index]):

'foo'.insert(-2, 'bar') # => "fobaro"
[ GitHub ]

  
# File 'string.c', line 5316

static VALUE
rb_str_insert(VALUE str, VALUE idx, VALUE str2)
{
    long pos = NUM2LONG(idx);

    if (pos == -1) {
	return rb_str_append(str, str2);
    }
    else if (pos < 0) {
	pos++;
    }
    rb_str_splice(str, pos, 0, str2);
    return str;
}

#inspectString

Returns a printable version of self, enclosed in double-quotes, and with special characters escaped:

s = "foo\tbar\tbaz\n"
# => "foo\tbar\tbaz\n"
s.inspect
# => "\"foo\\tbar\\tbaz\\n\""
[ GitHub ]

  
# File 'string.c', line 6456

VALUE
rb_str_inspect(VALUE str)
{
    int encidx = ENCODING_GET(str);
    rb_encoding *enc = rb_enc_from_index(encidx), *actenc;
    const char *p, *pend, *prev;
    char buf[CHAR_ESC_LEN + 1];
    VALUE result = rb_str_buf_new(0);
    rb_encoding *resenc = rb_default_internal_encoding();
    int unicode_p = rb_enc_unicode_p(enc);
    int asciicompat = rb_enc_asciicompat(enc);

    if (resenc == NULL) resenc = rb_default_external_encoding();
    if (!rb_enc_asciicompat(resenc)) resenc = rb_usascii_encoding();
    rb_enc_associate(result, resenc);
    str_buf_cat2(result, "\"");

    p = RSTRING_PTR(str); pend = RSTRING_END(str);
    prev = p;
    actenc = get_actual_encoding(encidx, str);
    if (actenc != enc) {
	enc = actenc;
	if (unicode_p) unicode_p = rb_enc_unicode_p(enc);
    }
    while (p < pend) {
	unsigned int c, cc;
	int n;

        n = rb_enc_precise_mbclen(p, pend, enc);
        if (!MBCLEN_CHARFOUND_P(n)) {
	    if (p > prev) str_buf_cat(result, prev, p - prev);
            n = rb_enc_mbminlen(enc);
            if (pend < p + n)
                n = (int)(pend - p);
            while (n--) {
                snprintf(buf, CHAR_ESC_LEN, "\\x%02X", *p & 0377);
                str_buf_cat(result, buf, strlen(buf));
                prev = ++p;
            }
	    continue;
	}
        n = MBCLEN_CHARFOUND_LEN(n);
	c = rb_enc_mbc_to_codepoint(p, pend, enc);
	p += n;
	if ((asciicompat || unicode_p) &&
	  (c == '"'|| c == '\\' ||
	    (c == '#' &&
             p < pend &&
             MBCLEN_CHARFOUND_P(rb_enc_precise_mbclen(p,pend,enc)) &&
             (cc = rb_enc_codepoint(p,pend,enc),
              (cc == '$' || cc == '@' || cc == '{'))))) {
	    if (p - n > prev) str_buf_cat(result, prev, p - n - prev);
	    str_buf_cat2(result, "\\");
	    if (asciicompat || enc == resenc) {
		prev = p - n;
		continue;
	    }
	}
	switch (c) {
	  case '\n': cc = 'n'; break;
	  case '\r': cc = 'r'; break;
	  case '\t': cc = 't'; break;
	  case '\f': cc = 'f'; break;
	  case '\013': cc = 'v'; break;
	  case '\010': cc = 'b'; break;
	  case '\007': cc = 'a'; break;
	  case 033: cc = 'e'; break;
	  default: cc = 0; break;
	}
	if (cc) {
	    if (p - n > prev) str_buf_cat(result, prev, p - n - prev);
	    buf[0] = '\\';
	    buf[1] = (char)cc;
	    str_buf_cat(result, buf, 2);
	    prev = p;
	    continue;
	}
	if ((enc == resenc && rb_enc_isprint(c, enc)) ||
	    (asciicompat && rb_enc_isascii(c, enc) && ISPRINT(c))) {
	    continue;
	}
	else {
	    if (p - n > prev) str_buf_cat(result, prev, p - n - prev);
	    rb_str_buf_cat_escaped_char(result, c, unicode_p);
	    prev = p;
	    continue;
	}
    }
    if (p > prev) str_buf_cat(result, prev, p - prev);
    str_buf_cat2(result, "\"");

    return result;
}

#internSymbol #to_symSymbol
Also known as: #to_sym

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"
[ GitHub ]

  
# File 'symbol.c', line 836

VALUE
rb_str_intern(VALUE str)
{
    VALUE sym;
#if USE_SYMBOL_GC
    rb_encoding *enc, *ascii;
    int type;
#else
    ID id;
#endif
    GLOBAL_SYMBOLS_ENTER(symbols);
    {
        sym = lookup_str_sym_with_lock(symbols, str);

        if (sym) {
            // ok
        }
        else {
#if USE_SYMBOL_GC
            enc = rb_enc_get(str);
            ascii = rb_usascii_encoding();
            if (enc != ascii && sym_check_asciionly(str)) {
                str = rb_str_dup(str);
                rb_enc_associate(str, ascii);
                OBJ_FREEZE(str);
                enc = ascii;
            }
            else {
                str = rb_str_dup(str);
                OBJ_FREEZE(str);
            }
            str = rb_fstring(str);
            type = rb_str_symname_type(str, IDSET_ATTRSET_FOR_INTERN);
            if (type < 0) type = ID_JUNK;
            sym = dsymbol_alloc(symbols, rb_cSymbol, str, enc, type);
#else
            id = intern_str(str, 0);
            sym = ID2SYM(id);
#endif
        }
    }
    GLOBAL_SYMBOLS_LEAVE();
    return sym;
}

#length

[ GitHub ]

#lines(separator = $/, chomp: false) ⇒ Array

Returns an array of lines in str split using the supplied record separator ($/ by default). This is a shorthand for str.each_line(separator, getline_args).to_a.

If #chomp is true, separator will be removed from the end of each line.

"hello\nworld\n".lines              #=> ["hello\n", "world\n"]
"hello  world".lines(' ')           #=> ["hello ", " ", "world"]
"hello\nworld\n".lines(chomp: true) #=> ["hello", "world"]

If a block is given, which is a deprecated form, works the same as #each_line.

[ GitHub ]

  
# File 'string.c', line 8939

static VALUE
rb_str_lines(int argc, VALUE *argv, VALUE str)
{
    VALUE ary = WANTARRAY("lines", 0);
    return rb_str_enumerate_lines(argc, argv, str, ary);
}

#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"
[ GitHub ]

  
# File 'string.c', line 10314

static VALUE
rb_str_ljust(int argc, VALUE *argv, VALUE str)
{
    return rb_str_justify(argc, argv, str, 'l');
}

#lstripString

Returns a copy of the receiver with leading whitespace removed. See also #rstrip and #strip.

Refer to #strip for the definition of whitespace.

"  hello  ".lstrip   #=> "hello  "
"hello".lstrip       #=> "hello"
[ GitHub ]

  
# File 'string.c', line 9640

static VALUE
rb_str_lstrip(VALUE str)
{
    char *start;
    long len, loffset;
    RSTRING_GETMEM(str, start, len);
    loffset = lstrip_offset(str, start, start+len, STR_ENC_GET(str));
    if (loffset <= 0) return str_duplicate(rb_cString, str);
    return rb_str_subseq(str, loffset, len - loffset);
}

#lstrip!self?

Removes leading whitespace from the receiver. Returns the altered receiver, or nil if no change was made. See also #rstrip! and #strip!.

Refer to #strip for the definition of whitespace.

"  hello  ".lstrip!  #=> "hello  "
"hello  ".lstrip!    #=> nil
"hello".lstrip!      #=> nil
[ GitHub ]

  
# File 'string.c', line 9604

static VALUE
rb_str_lstrip_bang(VALUE str)
{
    rb_encoding *enc;
    char *start, *s;
    long olen, loffset;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    RSTRING_GETMEM(str, start, olen);
    loffset = lstrip_offset(str, start, start+olen, enc);
    if (loffset > 0) {
	long len = olen-loffset;
	s = start + loffset;
	memmove(start, s, len);
	STR_SET_LEN(str, len);
	TERM_FILL(start+len, rb_enc_mbminlen(enc));
	return str;
    }
    return Qnil;
}

#match

[ GitHub ]

#match?Boolean

[ GitHub ]

#nextString Also known as: #succ

Returns the successor to self. The successor is calculated by incrementing characters.

The first character to be incremented is the rightmost alphanumeric: or, if no alphanumerics, the rightmost character:

'THX1138'.succ # => "THX1139"
'<<koala>>'.succ # => "<<koalb>>"
'***'.succ # => '**+'

The successor to a digit is another digit, “carrying” to the next-left character for a “rollover” from 9 to 0, and prepending another digit if necessary:

'00'.succ # => "01"
'09'.succ # => "10"
'99'.succ # => "100"

The successor to a letter is another letter of the same case, carrying to the next-left character for a rollover, and prepending another same-case letter if necessary:

'aa'.succ # => "ab"
'az'.succ # => "ba"
'zz'.succ # => "aaa"
'AA'.succ # => "AB"
'AZ'.succ # => "BA"
'ZZ'.succ # => "AAA"

The successor to a non-alphanumeric character is the next character in the underlying character set’s collating sequence, carrying to the next-left character for a rollover, and prepending another character if necessary:

s = 0.chr * 3
s # => "\x00\x00\x00"
s.succ # => "\x00\x00\x01"
s = 255.chr * 3
s # => "\xFF\xFF\xFF"
s.succ # => "\x01\x00\x00\x00"

Carrying can occur between and among mixtures of alphanumeric characters:

s = 'zz99zz99'
s.succ # => "aaa00aa00"
s = '99zz99zz'
s.succ # => "100aa00aa"

The successor to an empty String is a new empty String:

''.succ # => ""

next is an alias for #succ.

[ GitHub ]

  
# File 'string.c', line 4563

VALUE
rb_str_succ(VALUE orig)
{
    VALUE str;
    str = rb_str_new(RSTRING_PTR(orig), RSTRING_LEN(orig));
    rb_enc_cr_str_copy_for_substr(str, orig);
    return str_succ(str);
}

#next!self Also known as: #succ!

Equivalent to #succ, but modifies self in place; returns self.

next! is an alias for #succ!.

[ GitHub ]

  
# File 'string.c', line 4669

static VALUE
rb_str_succ_bang(VALUE str)
{
    rb_str_modify(str);
    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

If str starts with 0, radix indicators are honored. See Kernel.Integer.

[ GitHub ]

  
# File 'string.c', line 9967

static VALUE
rb_str_oct(VALUE str)
{
    return rb_str_to_inum(str, -8, FALSE);
}

#ordInteger

Returns the ::Integer ordinal of a one-character string.

"a".ord         #=> 97
[ GitHub ]

  
# File 'string.c', line 10136

static VALUE
rb_str_ord(VALUE s)
{
    unsigned int c;

    c = rb_enc_codepoint(RSTRING_PTR(s), RSTRING_END(s), STR_ENC_GET(s));
    return UINT2NUM(c);
}

#partition(sep) ⇒ Array, ... #partition(regexp) ⇒ Array, ...

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

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

  
# File 'string.c', line 10375

static VALUE
rb_str_partition(VALUE str, VALUE sep)
{
    long pos;

    sep = get_pat_quoted(sep, 0);
    if (RB_TYPE_P(sep, T_REGEXP)) {
	if (rb_reg_search(sep, str, 0, 0) < 0) {
            goto failed;
	}
	VALUE match = rb_backref_get();
	struct re_registers *regs = RMATCH_REGS(match);

        pos = BEG(0);
	sep = rb_str_subseq(str, pos, END(0) - pos);
    }
    else {
	pos = rb_str_index(str, sep, 0);
	if (pos < 0) goto failed;
    }
    return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
		          sep,
		          rb_str_subseq(str, pos+RSTRING_LEN(sep),
					     RSTRING_LEN(str)-pos-RSTRING_LEN(sep)));

  failed:
    return rb_ary_new3(3, str_duplicate(rb_cString, str), str_new_empty_String(str), str_new_empty_String(str));
}

#prepend

[ GitHub ]

#replace(other_string) ⇒ self Also known as: #initialize_copy

Replaces the contents of self with the contents of other_string:

s = 'foo'        # => "foo"
s.replace('bar') # => "bar"
[ GitHub ]

  
# File 'string.c', line 5841

VALUE
rb_str_replace(VALUE str, VALUE str2)
{
    str_modifiable(str);
    if (str == str2) return str;

    StringValue(str2);
    str_discard(str);
    return str_replace(str, str2);
}

#reverseString

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

'stressed'.reverse # => "desserts"
[ GitHub ]

  
# File 'string.c', line 6130

static VALUE
rb_str_reverse(VALUE str)
{
    rb_encoding *enc;
    VALUE rev;
    char *s, *e, *p;
    int cr;

    if (RSTRING_LEN(str) <= 1) return str_duplicate(rb_cString, str);
    enc = STR_ENC_GET(str);
    rev = rb_str_new(0, RSTRING_LEN(str));
    s = RSTRING_PTR(str); e = RSTRING_END(str);
    p = RSTRING_END(rev);
    cr = ENC_CODERANGE(str);

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

		p -= clen;
		memcpy(p, s, clen);
		s += clen;
	    }
	}
	else {
	    cr = rb_enc_asciicompat(enc) ?
		ENC_CODERANGE_7BIT : ENC_CODERANGE_VALID;
	    while (s < e) {
		int clen = rb_enc_mbclen(s, e, enc);

		if (clen > 1 || (*s & 0x80)) cr = ENC_CODERANGE_UNKNOWN;
		p -= clen;
		memcpy(p, s, clen);
		s += clen;
	    }
	}
    }
    STR_SET_LEN(rev, RSTRING_LEN(str));
    str_enc_copy(rev, str);
    ENC_CODERANGE_SET(rev, cr);

    return rev;
}

#reverse!self

Returns self with its characters reversed:

s = 'stressed'
s.reverse! # => "desserts"
s          # => "desserts"
[ GitHub ]

  
# File 'string.c', line 6193

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

	    str_modify_keep_cr(str);
	    s = RSTRING_PTR(str);
	    e = RSTRING_END(str) - 1;
	    while (s < e) {
		c = *s;
		*s++ = *e;
		*e-- = c;
	    }
	}
	else {
	    str_shared_replace(str, rb_str_reverse(str));
	}
    }
    else {
	str_modify_keep_cr(str);
    }
    return str;
}

#rindex

[ GitHub ]

#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"
[ GitHub ]

  
# File 'string.c', line 10334

static VALUE
rb_str_rjust(int argc, VALUE *argv, VALUE str)
{
    return rb_str_justify(argc, argv, str, 'r');
}

#rpartition(sep) ⇒ Array, ... #rpartition(regexp) ⇒ Array, ...

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

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

The match from the end means starting at the possible last position, not the last of longest matches.

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

To partition at the last longest match, needs to combine with negative lookbehind.

"hello".rpartition(/(?<!l)l+/)  #=> ["he", "ll", "o"]

Or #partition with negative lookforward.

"hello".partition(/l+(?!.*l)/)  #=> ["he", "ll", "o"]
[ GitHub ]

  
# File 'string.c', line 10433

static VALUE
rb_str_rpartition(VALUE str, VALUE sep)
{
    long pos = RSTRING_LEN(str);

    sep = get_pat_quoted(sep, 0);
    if (RB_TYPE_P(sep, T_REGEXP)) {
        if (rb_reg_search(sep, str, pos, 1) < 0) {
            goto failed;
        }
        VALUE match = rb_backref_get();
	struct re_registers *regs = RMATCH_REGS(match);

        pos = BEG(0);
        sep = rb_str_subseq(str, pos, END(0) - pos);
    }
    else {
	pos = rb_str_sublen(str, pos);
	pos = rb_str_rindex(str, sep, pos);
        if (pos < 0) {
            goto failed;
        }
        pos = rb_str_offset(str, pos);
    }

    return rb_ary_new3(3, rb_str_subseq(str, 0, pos),
		          sep,
		          rb_str_subseq(str, pos+RSTRING_LEN(sep),
					RSTRING_LEN(str)-pos-RSTRING_LEN(sep)));
  failed:
    return rb_ary_new3(3, str_new_empty_String(str), str_new_empty_String(str), str_duplicate(rb_cString, str));
}

#rstripString

Returns a copy of the receiver with trailing whitespace removed. See also #lstrip and #strip.

Refer to #strip for the definition of whitespace.

"  hello  ".rstrip   #=> "  hello"
"hello".rstrip       #=> "hello"
[ GitHub ]

  
# File 'string.c', line 9727

static VALUE
rb_str_rstrip(VALUE str)
{
    rb_encoding *enc;
    char *start;
    long olen, roffset;

    enc = STR_ENC_GET(str);
    RSTRING_GETMEM(str, start, olen);
    roffset = rstrip_offset(str, start, start+olen, enc);

    if (roffset <= 0) return str_duplicate(rb_cString, str);
    return rb_str_subseq(str, 0, olen-roffset);
}

#rstrip!self?

Removes trailing whitespace from the receiver. Returns the altered receiver, or nil if no change was made. See also #lstrip! and #strip!.

Refer to #strip for the definition of whitespace.

"  hello  ".rstrip!  #=> "  hello"
"  hello".rstrip!    #=> nil
"hello".rstrip!      #=> nil
[ GitHub ]

  
# File 'string.c', line 9692

static VALUE
rb_str_rstrip_bang(VALUE str)
{
    rb_encoding *enc;
    char *start;
    long olen, roffset;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    RSTRING_GETMEM(str, start, olen);
    roffset = rstrip_offset(str, start, start+olen, enc);
    if (roffset > 0) {
	long len = olen - roffset;

	STR_SET_LEN(str, len);
	TERM_FILL(start+len, rb_enc_mbminlen(enc));
	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
[ GitHub ]

  
# File 'string.c', line 9895

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

    pat = get_pat_quoted(pat, 1);
    mustnot_broken(str);
    if (!rb_block_given_p()) {
	VALUE ary = rb_ary_new();

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

    while (!NIL_P(result = scan_once(str, pat, &start, 1))) {
	last = prev;
	prev = start;
	rb_yield(result);
	str_mod_check(str, p, len);
    }
    if (last >= 0) rb_pat_search(pat, str, last, 1);
    return str;
}

#scrubString #scrub(repl) ⇒ String #scrub {|bytes| ... } ⇒ String

If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.

"abc\u3042\x81".scrub #=> "abc\u3042\uFFFD"
"abc\u3042\x81".scrub("*") #=> "abc\u3042*"
"abc\u3042\xE3\x80".scrub{|bytes| '<'bytes.unpack1('H*')'>' } #=> "abc\u3042<e380>"
[ GitHub ]

  
# File 'string.c', line 11135

static VALUE
str_scrub(int argc, VALUE *argv, VALUE str)
{
    VALUE repl = argc ? (rb_check_arity(argc, 0, 1), argv[0]) : Qnil;
    VALUE new = rb_str_scrub(str, repl);
    return NIL_P(new) ? str_duplicate(rb_cString, str): new;
}

#scrub!String #scrub!(repl) ⇒ String #scrub! {|bytes| ... } ⇒ String

If the string is invalid byte sequence then replace invalid bytes with given replacement character, else returns self. If block is given, replace invalid bytes with returned value of the block.

"abc\u3042\x81".scrub! #=> "abc\u3042\uFFFD"
"abc\u3042\x81".scrub!("*") #=> "abc\u3042*"
"abc\u3042\xE3\x80".scrub!{|bytes| '<'bytes.unpack1('H*')'>' } #=> "abc\u3042<e380>"
[ GitHub ]

  
# File 'string.c', line 11157

static VALUE
str_scrub_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE repl = argc ? (rb_check_arity(argc, 0, 1), argv[0]) : Qnil;
    VALUE new = rb_str_scrub(str, repl);
    if (!NIL_P(new)) rb_str_replace(str, new);
    return str;
}

#setbyte(index, integer) ⇒ Integer

Sets the byte at zero-based #index to integer; returns integer:

s = 'abcde'      # => "abcde"
s.setbyte(0, 98) # => 98
s                # => "bbcde"

Related: #getbyte.

[ GitHub ]

  
# File 'string.c', line 5931

static VALUE
rb_str_setbyte(VALUE str, VALUE index, VALUE value)
{
    long pos = NUM2LONG(index);
    long len = RSTRING_LEN(str);
    char *ptr, *head, *left = 0;
    rb_encoding *enc;
    int cr = ENC_CODERANGE_UNKNOWN, width, nlen;

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

    VALUE v = rb_to_int(value);
    VALUE w = rb_int_and(v, INT2FIX(0xff));
    char byte = (char)(NUM2INT(w) & 0xFF);

    if (!str_independent(str))
	str_make_independent(str);
    enc = STR_ENC_GET(str);
    head = RSTRING_PTR(str);
    ptr = &head[pos];
    if (!STR_EMBED_P(str)) {
	cr = ENC_CODERANGE(str);
	switch (cr) {
	  case ENC_CODERANGE_7BIT:
            left = ptr;
	    *ptr = byte;
	    if (ISASCII(byte)) goto end;
	    nlen = rb_enc_precise_mbclen(left, head+len, enc);
	    if (!MBCLEN_CHARFOUND_P(nlen))
		ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN);
	    else
		ENC_CODERANGE_SET(str, ENC_CODERANGE_VALID);
	    goto end;
	  case ENC_CODERANGE_VALID:
	    left = rb_enc_left_char_head(head, ptr, head+len, enc);
	    width = rb_enc_precise_mbclen(left, head+len, enc);
	    *ptr = byte;
	    nlen = rb_enc_precise_mbclen(left, head+len, enc);
	    if (!MBCLEN_CHARFOUND_P(nlen))
		ENC_CODERANGE_SET(str, ENC_CODERANGE_BROKEN);
	    else if (MBCLEN_CHARFOUND_LEN(nlen) != width || ISASCII(byte))
		ENC_CODERANGE_CLEAR(str);
	    goto end;
	}
    }
    ENC_CODERANGE_CLEAR(str);
    *ptr = byte;

  end:
    return value;
}

#size

[ GitHub ]

#[](index) ⇒ String? #[](start, length) ⇒ String? #[](range) ⇒ String? #[](substring) ⇒ String?

Alias for #[].

#slice!(index) ⇒ String? #slice!(start, length) ⇒ String? #slice!(range) ⇒ String? #slice!(regexp, capture = 0) ⇒ String? #slice!(substring) ⇒ String?

Removes the substring of self specified by the arguments; returns the removed substring.

See #[] for details about the arguments that specify the substring.

A few examples:

string = "This is a string"
string.slice!(2)        #=> "i"
string.slice!(3..6)     #=> " is "
string.slice!(/s.*t/)   #=> "sa st"
string.slice!("r")      #=> "r"
string                  #=> "Thing"
[ GitHub ]

  
# File 'string.c', line 5356

static VALUE
rb_str_slice_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE result = Qnil;
    VALUE indx;
    long beg, len = 1;
    char *p;

    rb_check_arity(argc, 1, 2);
    str_modify_keep_cr(str);
    indx = argv[0];
    if (RB_TYPE_P(indx, T_REGEXP)) {
	if (rb_reg_search(indx, str, 0, 0) < 0) return Qnil;
	VALUE match = rb_backref_get();
	struct re_registers *regs = RMATCH_REGS(match);
	int nth = 0;
	if (argc > 1 && (nth = rb_reg_backref_number(match, argv[1])) < 0) {
	    if ((nth += regs->num_regs) <= 0) return Qnil;
	}
	else if (nth >= regs->num_regs) return Qnil;
	beg = BEG(nth);
	len = END(nth) - beg;
        goto subseq;
    }
    else if (argc == 2) {
	beg = NUM2LONG(indx);
	len = NUM2LONG(argv[1]);
        goto num_index;
    }
    else if (FIXNUM_P(indx)) {
	beg = FIX2LONG(indx);
	if (!(p = rb_str_subpos(str, beg, &len))) return Qnil;
	if (!len) return Qnil;
	beg = p - RSTRING_PTR(str);
	goto subseq;
    }
    else if (RB_TYPE_P(indx, T_STRING)) {
	beg = rb_str_index(str, indx, 0);
	if (beg == -1) return Qnil;
	len = RSTRING_LEN(indx);
        result = str_duplicate(rb_cString, indx);
        goto squash;
    }
    else {
	switch (rb_range_beg_len(indx, &beg, &len, str_strlen(str, NULL), 0)) {
	  case Qnil:
	    return Qnil;
	  case Qfalse:
	    beg = NUM2LONG(indx);
	    if (!(p = rb_str_subpos(str, beg, &len))) return Qnil;
	    if (!len) return Qnil;
	    beg = p - RSTRING_PTR(str);
	    goto subseq;
	  default:
	    goto num_index;
	}
    }

  num_index:
    if (!(p = rb_str_subpos(str, beg, &len))) return Qnil;
    beg = p - RSTRING_PTR(str);

  subseq:
    result = rb_str_new(RSTRING_PTR(str)+beg, len);
    rb_enc_cr_str_copy_for_substr(result, str);

  squash:
    if (len > 0) {
	if (beg == 0) {
	    rb_str_drop_bytes(str, len);
	}
	else {
	    char *sptr = RSTRING_PTR(str);
	    long slen = RSTRING_LEN(str);
	    if (beg + len > slen) /* pathological check */
		len = slen - beg;
	    memmove(sptr + beg,
		    sptr + beg + len,
		    slen - (beg + len));
	    slen -= len;
	    STR_SET_LEN(str, slen);
	    TERM_FILL(&sptr[slen], TERM_LEN(str));
	    ENC_CODERANGE_CLEAR(str);
	}
    }
    return result;
}

#split(pattern = nil, [limit]) ⇒ Array #split(pattern = nil, [limit]) {|sub| ... } ⇒ String

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 and trailing whitespace and runs of contiguous whitespace characters ignored.

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

If pattern is nil, 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 split substrings will be returned (captured groups will be returned as well, but are not counted towards the limit). 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.

When the input str is empty an empty ::Array is returned as the string is considered to have no fields to split.

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

"1:2:3".split(/(:)()()/, 2)     #=> ["1", ":", "", "", "2:3"]

"".split(',', -1)               #=> []

If a block is given, invoke the block with each split substring.

[ GitHub ]

  
# File 'string.c', line 8457

static VALUE
rb_str_split_m(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    VALUE spat;
    VALUE limit;
    split_type_t split_type;
    long beg, end, i = 0, empty_count = -1;
    int lim = 0;
    VALUE result, tmp;

    result = rb_block_given_p() ? Qfalse : Qnil;
    if (rb_scan_args(argc, argv, "02", &spat, &limit) == 2) {
	lim = NUM2INT(limit);
	if (lim <= 0) limit = Qnil;
	else if (lim == 1) {
	    if (RSTRING_LEN(str) == 0)
                return result ? rb_ary_new2(0) : str;
            tmp = str_duplicate(rb_cString, str);
	    if (!result) {
		rb_yield(tmp);
                return str;
	    }
	    return rb_ary_new3(1, tmp);
	}
	i = 1;
    }
    if (NIL_P(limit) && !lim) empty_count = 0;

    enc = STR_ENC_GET(str);
    split_type = SPLIT_TYPE_REGEXP;
    if (!NIL_P(spat)) {
	spat = get_pat_quoted(spat, 0);
    }
    else if (NIL_P(spat = rb_fs)) {
	split_type = SPLIT_TYPE_AWK;
    }
    else if (!(spat = rb_fs_check(spat))) {
	rb_raise(rb_eTypeError, "value of $; must be String or Regexp");
    }
    else {
        rb_category_warn(RB_WARN_CATEGORY_DEPRECATED, "$; is set to non-nil value");
    }
    if (split_type != SPLIT_TYPE_AWK) {
        switch (BUILTIN_TYPE(spat)) {
          case T_REGEXP:
            rb_reg_options(spat); /* check if uninitialized */
            tmp = RREGEXP_SRC(spat);
            split_type = literal_split_pattern(tmp, SPLIT_TYPE_REGEXP);
            if (split_type == SPLIT_TYPE_AWK) {
                spat = tmp;
                split_type = SPLIT_TYPE_STRING;
            }
            break;

          case T_STRING:
	    mustnot_broken(spat);
            split_type = literal_split_pattern(spat, SPLIT_TYPE_STRING);
            break;

          default:
            UNREACHABLE_RETURN(Qnil);
	}
    }

#define SPLIT_STR(beg, len) (empty_count = split_string(result, str, beg, len, empty_count))

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

	end = beg;
	if (is_ascii_string(str)) {
	    while (ptr < eptr) {
		c = (unsigned char)*ptr++;
		if (skip) {
		    if (ascii_isspace(c)) {
			beg = ptr - bptr;
		    }
		    else {
			end = ptr - bptr;
			skip = 0;
			if (!NIL_P(limit) && lim <= i) break;
		    }
		}
		else if (ascii_isspace(c)) {
		    SPLIT_STR(beg, end-beg);
		    skip = 1;
		    beg = ptr - bptr;
		    if (!NIL_P(limit)) ++i;
		}
		else {
		    end = ptr - bptr;
		}
	    }
	}
	else {
	    while (ptr < eptr) {
		int n;

		c = rb_enc_codepoint_len(ptr, eptr, &n, enc);
		ptr += n;
		if (skip) {
		    if (rb_isspace(c)) {
			beg = ptr - bptr;
		    }
		    else {
			end = ptr - bptr;
			skip = 0;
			if (!NIL_P(limit) && lim <= i) break;
		    }
		}
		else if (rb_isspace(c)) {
		    SPLIT_STR(beg, end-beg);
		    skip = 1;
		    beg = ptr - bptr;
		    if (!NIL_P(limit)) ++i;
		}
		else {
		    end = ptr - bptr;
		}
	    }
	}
    }
    else if (split_type == SPLIT_TYPE_STRING) {
	char *str_start = ptr;
	char *substr_start = ptr;
	char *sptr = RSTRING_PTR(spat);
	long slen = RSTRING_LEN(spat);

	mustnot_broken(str);
	enc = rb_enc_check(str, spat);
	while (ptr < eptr &&
	       (end = rb_memsearch(sptr, slen, ptr, eptr - ptr, enc)) >= 0) {
	    /* Check we are at the start of a char */
	    char *t = rb_enc_right_char_head(ptr, ptr + end, eptr, enc);
	    if (t != ptr + end) {
		ptr = t;
		continue;
	    }
	    SPLIT_STR(substr_start - str_start, (ptr+end) - substr_start);
	    ptr += end + slen;
	    substr_start = ptr;
	    if (!NIL_P(limit) && lim <= ++i) break;
	}
	beg = ptr - str_start;
    }
    else if (split_type == SPLIT_TYPE_CHARS) {
        char *str_start = ptr;
        int n;

        mustnot_broken(str);
        enc = rb_enc_get(str);
        while (ptr < eptr &&
               (n = rb_enc_precise_mbclen(ptr, eptr, enc)) > 0) {
            SPLIT_STR(ptr - str_start, n);
            ptr += n;
            if (!NIL_P(limit) && lim <= ++i) break;
        }
        beg = ptr - str_start;
    }
    else {
	long len = RSTRING_LEN(str);
	long start = beg;
	long idx;
	int last_null = 0;
	struct re_registers *regs;
        VALUE match = 0;

        for (; rb_reg_search(spat, str, start, 0) >= 0;
             (match ? (rb_match_unbusy(match), rb_backref_set(match)) : (void)0)) {
            match = rb_backref_get();
            if (!result) rb_match_busy(match);
            regs = RMATCH_REGS(match);
            end = BEG(0);
	    if (start == end && BEG(0) == END(0)) {
		if (!ptr) {
		    SPLIT_STR(0, 0);
		    break;
		}
		else if (last_null == 1) {
                    SPLIT_STR(beg, rb_enc_fast_mbclen(ptr+beg, eptr, enc));
		    beg = start;
		}
		else {
                    if (start == len)
                        start++;
                    else
                        start += rb_enc_fast_mbclen(ptr+start,eptr,enc);
		    last_null = 1;
		    continue;
		}
	    }
	    else {
		SPLIT_STR(beg, end-beg);
		beg = start = END(0);
	    }
	    last_null = 0;

	    for (idx=1; idx < regs->num_regs; idx++) {
		if (BEG(idx) == -1) continue;
		SPLIT_STR(BEG(idx), END(idx)-BEG(idx));
	    }
	    if (!NIL_P(limit) && lim <= ++i) break;
	}
        if (match) rb_match_unbusy(match);
    }
    if (RSTRING_LEN(str) > 0 && (!NIL_P(limit) || RSTRING_LEN(str) > beg || lim < 0)) {
	SPLIT_STR(beg, RSTRING_LEN(str)-beg);
    }

    return result ? result : str;
}

#squeeze([other_str]*) ⇒ String

Builds a set of characters from the other_str parameter(s) using the procedure described for #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"
[ GitHub ]

  
# File 'string.c', line 8171

static VALUE
rb_str_squeeze(int argc, VALUE *argv, VALUE str)
{
    str = str_duplicate(rb_cString, 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.

[ GitHub ]

  
# File 'string.c', line 8080

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

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

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

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

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

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

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

    TERM_FILL((char *)t, TERM_LEN(str));
    if ((char *)t - RSTRING_PTR(str) != RSTRING_LEN(str)) {
        STR_SET_LEN(str, (char *)t - RSTRING_PTR(str));
	modify = 1;
    }

    if (modify) return str;
    return Qnil;
}

#start_with?([prefixes]+) ⇒ Boolean

Returns true if str starts with one of the prefixes given. Each of the prefixes should be a String or a ::Regexp.

"hello".start_with?("hell")               #=> true
"hello".start_with?(/H/i)                 #=> true

# returns true if one of the prefixes matches.
"hello".start_with?("heaven", "hell")     #=> true
"hello".start_with?("heaven", "paradise") #=> false
[ GitHub ]

  
# File 'string.c', line 10481

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

    for (i=0; i<argc; i++) {
	VALUE tmp = argv[i];
	if (RB_TYPE_P(tmp, T_REGEXP)) {
	    if (rb_reg_start_with_p(tmp, str))
		return Qtrue;
	}
	else {
	    StringValue(tmp);
	    rb_enc_check(str, tmp);
	    if (RSTRING_LEN(str) < RSTRING_LEN(tmp)) continue;
	    if (memcmp(RSTRING_PTR(str), RSTRING_PTR(tmp), RSTRING_LEN(tmp)) == 0)
		return Qtrue;
	}
    }
    return Qfalse;
}

#stripString

Returns a copy of the receiver with leading and trailing whitespace removed.

Whitespace is defined as any of the following characters: null, horizontal tab, line feed, vertical tab, form feed, carriage return, space.

"    hello    ".strip   #=> "hello"
"\tgoodbye\r\n".strip   #=> "goodbye"
"\x00\t\n\v\f\r ".strip #=> ""
"hello".strip           #=> "hello"
[ GitHub ]

  
# File 'string.c', line 9798

static VALUE
rb_str_strip(VALUE str)
{
    char *start;
    long olen, loffset, roffset;
    rb_encoding *enc = STR_ENC_GET(str);

    RSTRING_GETMEM(str, start, olen);
    loffset = lstrip_offset(str, start, start+olen, enc);
    roffset = rstrip_offset(str, start+loffset, start+olen, enc);

    if (loffset <= 0 && roffset <= 0) return str_duplicate(rb_cString, str);
    return rb_str_subseq(str, loffset, olen-loffset-roffset);
}

#strip!self?

Removes leading and trailing whitespace from the receiver. Returns the altered receiver, or nil if there was no change.

Refer to #strip for the definition of whitespace.

"  hello  ".strip!  #=> "hello"
"hello".strip!      #=> nil
[ GitHub ]

  
# File 'string.c', line 9756

static VALUE
rb_str_strip_bang(VALUE str)
{
    char *start;
    long olen, loffset, roffset;
    rb_encoding *enc;

    str_modify_keep_cr(str);
    enc = STR_ENC_GET(str);
    RSTRING_GETMEM(str, start, olen);
    loffset = lstrip_offset(str, start, start+olen, enc);
    roffset = rstrip_offset(str, start+loffset, start+olen, enc);

    if (loffset > 0 || roffset > 0) {
	long len = olen-roffset;
	if (loffset > 0) {
	    len -= loffset;
	    memmove(start, start + loffset, len);
	}
	STR_SET_LEN(str, len);
	TERM_FILL(start+len, rb_enc_mbminlen(enc));
	return str;
    }
    return Qnil;
}

#sub(pattern, replacement) ⇒ String #sub(pattern) {|match| ... } ⇒ String

Returns a copy of self with only the first occurrence (not all occurrences) of the given pattern replaced.

See Substitution Methods.

Related: #sub!, #gsub, #gsub!.

[ GitHub ]

  
# File 'string.c', line 5651

static VALUE
rb_str_sub(int argc, VALUE *argv, VALUE str)
{
    str = str_duplicate(rb_cString, str);
    rb_str_sub_bang(argc, argv, str);
    return str;
}

#sub!(pattern, replacement) ⇒ self? #sub!(pattern) {|match| ... } ⇒ self?

Returns self with only the first occurrence (not all occurrences) of the given pattern replaced.

See Substitution Methods.

Related: #sub, #gsub, #gsub!.

[ GitHub ]

  
# File 'string.c', line 5528

static VALUE
rb_str_sub_bang(int argc, VALUE *argv, VALUE str)
{
    VALUE pat, repl, hash = Qnil;
    int iter = 0;
    long plen;
    int min_arity = rb_block_given_p() ? 1 : 2;
    long beg;

    rb_check_arity(argc, min_arity, 2);
    if (argc == 1) {
	iter = 1;
    }
    else {
	repl = argv[1];
	hash = rb_check_hash_type(argv[1]);
	if (NIL_P(hash)) {
	    StringValue(repl);
	}
    }

    pat = get_pat_quoted(argv[0], 1);

    str_modifiable(str);
    beg = rb_pat_search(pat, str, 0, 1);
    if (beg >= 0) {
	rb_encoding *enc;
	int cr = ENC_CODERANGE(str);
	long beg0, end0;
	VALUE match, match0 = Qnil;
	struct re_registers *regs;
	char *p, *rp;
	long len, rlen;

	match = rb_backref_get();
	regs = RMATCH_REGS(match);
	if (RB_TYPE_P(pat, T_STRING)) {
	    beg0 = beg;
	    end0 = beg0 + RSTRING_LEN(pat);
	    match0 = pat;
	}
	else {
	    beg0 = BEG(0);
	    end0 = END(0);
	    if (iter) match0 = rb_reg_nth_match(0, match);
	}

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

            if (iter) {
                repl = rb_obj_as_string(rb_yield(match0));
            }
            else {
                repl = rb_hash_aref(hash, rb_str_subseq(str, beg0, end0 - beg0));
                repl = rb_obj_as_string(repl);
            }
	    str_mod_check(str, p, len);
	    rb_check_frozen(str);
	}
	else {
	    repl = rb_reg_regsub(repl, str, regs, RB_TYPE_P(pat, T_STRING) ? Qnil : pat);
	}

        enc = rb_enc_compatible(str, repl);
        if (!enc) {
            rb_encoding *str_enc = STR_ENC_GET(str);
	    p = RSTRING_PTR(str); len = RSTRING_LEN(str);
	    if (coderange_scan(p, beg0, str_enc) != ENC_CODERANGE_7BIT ||
		coderange_scan(p+end0, len-end0, str_enc) != ENC_CODERANGE_7BIT) {
                rb_raise(rb_eEncCompatError, "incompatible character encodings: %s and %s",
			 rb_enc_name(str_enc),
			 rb_enc_name(STR_ENC_GET(repl)));
            }
            enc = STR_ENC_GET(repl);
        }
	rb_str_modify(str);
	rb_enc_associate(str, enc);
	if (ENC_CODERANGE_UNKNOWN < cr && cr < ENC_CODERANGE_BROKEN) {
	    int cr2 = ENC_CODERANGE(repl);
            if (cr2 == ENC_CODERANGE_BROKEN ||
                (cr == ENC_CODERANGE_VALID && cr2 == ENC_CODERANGE_7BIT))
                cr = ENC_CODERANGE_UNKNOWN;
            else
                cr = cr2;
	}
	plen = end0 - beg0;
        rlen = RSTRING_LEN(repl);
	len = RSTRING_LEN(str);
	if (rlen > plen) {
	    RESIZE_CAPA(str, len + rlen - plen);
	}
	p = RSTRING_PTR(str);
	if (rlen != plen) {
	    memmove(p + beg0 + rlen, p + beg0 + plen, len - beg0 - plen);
	}
        rp = RSTRING_PTR(repl);
        memmove(p + beg0, rp, rlen);
	len += rlen - plen;
	STR_SET_LEN(str, len);
	TERM_FILL(&RSTRING_PTR(str)[len], TERM_LEN(str));
	ENC_CODERANGE_SET(str, cr);

	return str;
    }
    return Qnil;
}

#nextString #succString

Alias for #next.

#next!self #succ!self

Alias for #next!.

#sum(n = 16) ⇒ Integer

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

[ GitHub ]

  
# File 'string.c', line 10155

static VALUE
rb_str_sum(int argc, VALUE *argv, VALUE str)
{
    int bits = 16;
    char *ptr, *p, *pend;
    long len;
    VALUE sum = INT2FIX(0);
    unsigned long sum0 = 0;

    if (rb_check_arity(argc, 0, 1) && (bits = NUM2INT(argv[0])) < 0) {
        bits = 0;
    }
    ptr = p = RSTRING_PTR(str);
    len = RSTRING_LEN(str);
    pend = p + len;

    while (p < pend) {
        if (FIXNUM_MAX - UCHAR_MAX < sum0) {
            sum = rb_funcall(sum, '+', 1, LONG2FIX(sum0));
            str_mod_check(str, ptr, len);
            sum0 = 0;
        }
        sum0 += (unsigned char)*p;
        p++;
    }

    if (bits == 0) {
        if (sum0) {
            sum = rb_funcall(sum, '+', 1, LONG2FIX(sum0));
        }
    }
    else {
        if (sum == INT2FIX(0)) {
            if (bits < (int)sizeof(long)*CHAR_BIT) {
                sum0 &= (((unsigned long)1)<<bits)-1;
            }
            sum = LONG2FIX(sum0);
        }
        else {
            VALUE mod;

            if (sum0) {
                sum = rb_funcall(sum, '+', 1, LONG2FIX(sum0));
            }

            mod = rb_funcall(INT2FIX(1), idLTLT, 1, INT2FIX(bits));
            mod = rb_funcall(mod, '-', 1, INT2FIX(1));
            sum = rb_funcall(sum, '&', 1, mod);
        }
    }
    return sum;
}

#swapcase(*options) ⇒ String

Returns a string containing the characters in self, with cases reversed; each uppercase character is downcased; each lowercase character is upcased:

s = 'Hello World!' # => "Hello World!"
s.swapcase         # => "hELLO wORLD!"

The casing may be affected by the given options; see Case Mapping.

Related: #swapcase!.

[ GitHub ]

  
# File 'string.c', line 7501

static VALUE
rb_str_swapcase(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_UPCASE | ONIGENC_CASE_DOWNCASE;
    VALUE ret;

    flags = check_case_options(argc, argv, flags);
    enc = str_true_enc(str);
    if (RSTRING_LEN(str) == 0 || !RSTRING_PTR(str)) return str_duplicate(rb_cString, str);
    if (flags&ONIGENC_CASE_ASCII_ONLY) {
        ret = rb_str_new(0, RSTRING_LEN(str));
        rb_str_ascii_casemap(str, ret, &flags, enc);
    }
    else {
        ret = rb_str_casemap(str, &flags, enc);
    }
    return ret;
}

#swapcase!(*options) ⇒ self?

Upcases each lowercase character in self; downcases uppercase character; returns self if any changes were made, nil otherwise:

s = 'Hello World!' # => "Hello World!"
s.swapcase!        # => "hELLO wORLD!"
s                  # => "Hello World!"
''.swapcase!       # => nil

The casing may be affected by the given options; see Case Mapping.

Related: #swapcase.

[ GitHub ]

  
# File 'string.c', line 7464

static VALUE
rb_str_swapcase_bang(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_UPCASE | ONIGENC_CASE_DOWNCASE;

    flags = check_case_options(argc, argv, flags);
    str_modify_keep_cr(str);
    enc = str_true_enc(str);
    if (flags&ONIGENC_CASE_ASCII_ONLY)
        rb_str_ascii_casemap(str, str, &flags, enc);
    else
	str_shared_replace(str, rb_str_casemap(str, &flags, enc));

    if (ONIGENC_CASE_MODIFIED&flags) return str;
    return Qnil;
}

#to_cComplex

Returns a complex which denotes the string form. The parser ignores leading whitespaces and trailing garbage. Any digit sequences can be separated by an underscore. Returns zero for null or garbage string.

'9'.to_c           #=> (9+0i)
'2.5'.to_c         #=> (2.5+0i)
'2.5/1'.to_c       #=> ((5/2)+0i)
'-3/2'.to_c        #=> ((-3/2)+0i)
'-i'.to_c          #=> (0-1i)
'45i'.to_c         #=> (0+45i)
'3-4i'.to_c        #=> (3-4i)
'-4e2-4e-2i'.to_c  #=> (-400.0-0.04i)
'-0.0-0.0i'.to_c   #=> (-0.0-0.0i)
'1/2+3/4i'.to_c    #=> ((1/2)+(3/4)*i)
'ruby'.to_c        #=> (0+0i)

See Kernel.Complex.

[ GitHub ]

  
# File 'complex.c', line 2017

static VALUE
string_to_c(VALUE self)
{
    char *s;
    VALUE num;

    rb_must_asciicompat(self);

    s = RSTRING_PTR(self);

    if (s && s[RSTRING_LEN(self)]) {
	rb_str_modify(self);
	s = RSTRING_PTR(self);
	s[RSTRING_LEN(self)] = '\0';
    }

    if (!s)
	s = (char *)"";

    (void)parse_comp(s, 0, &num);

    return num;
}

#to_fFloat

Returns the result of interpreting leading characters in self as a ::Float:

'3.14159'.to_f  # => 3.14159
  '1.234e-2'.to_f # => 0.01234

Characters past a leading valid number (in the given base) are ignored:

'3.14 (pi to two places)'.to_f # => 3.14

Returns zero if there is no leading valid number:

'abcdef'.to_f # => 0.0
[ GitHub ]

  
# File 'string.c', line 6298

static VALUE
rb_str_to_f(VALUE str)
{
    return DBL2NUM(rb_str_to_dbl(str, FALSE));
}

#to_i(base = 10) ⇒ Integer

Returns the result of interpreting leading characters in self as an integer in the given base (which must be in (2..36)):

'123456'.to_i     # => 123456
'123def'.to_i(16) # => 1195503

Characters past a leading valid number (in the given base) are ignored:

'12.345'.to_i   # => 12
'12345'.to_i(2) # => 1

Returns zero if there is no leading valid number:

'abcdef'.to_i # => 0
'2'.to_i(2)   # => 0
[ GitHub ]

  
# File 'string.c', line 6267

static VALUE
rb_str_to_i(int argc, VALUE *argv, VALUE str)
{
    int base = 10;

    if (rb_check_arity(argc, 0, 1) && (base = NUM2INT(argv[0])) < 0) {
	rb_raise(rb_eArgError, "invalid radix %d", base);
    }
    return rb_str_to_inum(str, base, FALSE);
}

#to_rRational

Returns the result of interpreting leading characters in str as a rational. Leading whitespace and extraneous characters past the end of a valid number are ignored. Digit sequences can be separated by an underscore. If there is not a valid number at the start of str, zero is returned. This method never raises an exception.

'  2  '.to_r       #=> (2/1)
'300/2'.to_r       #=> (150/1)
'-9.2'.to_r        #=> (-46/5)
'-9.2e2'.to_r      #=> (-920/1)
'1_234_567'.to_r   #=> (1234567/1)
'21 June 09'.to_r  #=> (21/1)
'21/06/09'.to_r    #=> (7/2)
'BWV 1079'.to_r    #=> (0/1)

NOTE: “0.3”.to_r isn’t the same as 0.3.to_r. The former is equivalent to “3/10”.to_r, but the latter isn’t so.

"0.3".to_r == 3/10r  #=> true
0.3.to_r   == 3/10r  #=> false

See also Kernel.Rational.

[ GitHub ]

  
# File 'rational.c', line 2535

static VALUE
string_to_r(VALUE self)
{
    VALUE num;

    rb_must_asciicompat(self);

    num = parse_rat(RSTRING_PTR(self), RSTRING_END(self), 0, TRUE);

    if (RB_FLOAT_TYPE_P(num) && !FLOAT_ZERO_P(num))
	rb_raise(rb_eFloatDomainError, "Infinity");
    return num;
}

#to_sself, String Also known as: #to_str

Returns self if self is a String, or self converted to a String if self is a subclass of String.

#to_str is an alias for to_s.

[ GitHub ]

  
# File 'string.c', line 6316

static VALUE
rb_str_to_s(VALUE str)
{
    if (rb_obj_class(str) != rb_cString) {
	return str_duplicate(rb_cString, str);
    }
    return str;
}

#to_sself, String #to_strself, String

Alias for #to_s.

#internSymbol #to_symSymbol

Alias for #intern.

#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 in order to maintain the correspondence.

"hello".tr('el', 'ip')      #=> "hippo"
"hello".tr('aeiou', '*')    #=> "h*ll*"
"hello".tr('aeiou', 'AA*')  #=> "hAll*"

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('a-y', 'b-z')    #=> "ifmmp"
"hello".tr('^aeiou', '*')   #=> "*e**o"

The backslash character \ can be used to escape ^ or - and is otherwise ignored unless it appears at the end of a range or the end of the from_str or #to_str:

"hello^world".tr("\\^aeiou", "*") #=> "h*ll**w*rld"
"hello-world".tr("a\\-eo", "*")   #=> "h*ll**w*rld"

"hello\r\nworld".tr("\r", "")   #=> "hello\nworld"
"hello\r\nworld".tr("\\r", "")  #=> "hello\r\nwold"
"hello\r\nworld".tr("\\\r", "") #=> "hello\nworld"

"X['\\b']".tr("X\\", "")   #=> "['b']"
"X['\\b']".tr("X-\\]", "") #=> "'b'"
[ GitHub ]

  
# File 'string.c', line 7883

static VALUE
rb_str_tr(VALUE str, VALUE src, VALUE repl)
{
    str = str_duplicate(rb_cString, str);
    tr_trans(str, src, repl, 0);
    return str;
}

#tr!(from_str, to_str) ⇒ String?

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

[ GitHub ]

  
# File 'string.c', line 7841

static VALUE
rb_str_tr_bang(VALUE str, VALUE src, VALUE repl)
{
    return tr_trans(str, src, repl, 0);
}

#tr_s(from_str, to_str) ⇒ String

Processes a copy of str as described under #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"
[ GitHub ]

  
# File 'string.c', line 8208

static VALUE
rb_str_tr_s(VALUE str, VALUE src, VALUE repl)
{
    str = str_duplicate(rb_cString, str);
    tr_trans(str, src, repl, 1);
    return str;
}

#tr_s!(from_str, to_str) ⇒ String?

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

[ GitHub ]

  
# File 'string.c', line 8188

static VALUE
rb_str_tr_s_bang(VALUE str, VALUE src, VALUE repl)
{
    return tr_trans(str, src, repl, 1);
}

#undumpString

Returns an unescaped version of self:

s_orig = "\f\x00\xff\\\""    # => "\f\u0000\xFF\\\""
s_dumped = s_orig.dump       # => "\"\\f\\x00\\xFF\\\\\\\"\""
s_undumped = s_dumped.undump # => "\f\u0000\xFF\\\""
s_undumped == s_orig         # => true

Related: #dump (inverse of undump).

[ GitHub ]

  
# File 'string.c', line 6862

static VALUE
str_undump(VALUE str)
{
    const char *s = RSTRING_PTR(str);
    const char *s_end = RSTRING_END(str);
    rb_encoding *enc = rb_enc_get(str);
    VALUE undumped = rb_enc_str_new(s, 0L, enc);
    bool utf8 = false;
    bool binary = false;
    int w;

    rb_must_asciicompat(str);
    if (rb_str_is_ascii_only_p(str) == Qfalse) {
	rb_raise(rb_eRuntimeError, "non-ASCII character detected");
    }
    if (!str_null_check(str, &w)) {
	rb_raise(rb_eRuntimeError, "string contains null byte");
    }
    if (RSTRING_LEN(str) < 2) goto invalid_format;
    if (*s != '"') goto invalid_format;

    /* strip '"' at the start */
    s++;

    for (;;) {
	if (s >= s_end) {
	    rb_raise(rb_eRuntimeError, "unterminated dumped string");
	}

	if (*s == '"') {
	    /* epilogue */
	    s++;
	    if (s == s_end) {
		/* ascii compatible dumped string */
		break;
	    }
	    else {
		static const char force_encoding_suffix[] = ".force_encoding(\""; /* "\")" */
		static const char dup_suffix[] = ".dup";
		const char *encname;
		int encidx;
		ptrdiff_t size;

		/* check separately for strings dumped by older versions */
		size = sizeof(dup_suffix) - 1;
		if (s_end - s > size && memcmp(s, dup_suffix, size) == 0) s += size;

		size = sizeof(force_encoding_suffix) - 1;
		if (s_end - s <= size) goto invalid_format;
		if (memcmp(s, force_encoding_suffix, size) != 0) goto invalid_format;
		s += size;

		if (utf8) {
		    rb_raise(rb_eRuntimeError, "dumped string contained Unicode escape but used force_encoding");
		}

		encname = s;
		s = memchr(s, '"', s_end-s);
		size = s - encname;
		if (!s) goto invalid_format;
		if (s_end - s != 2) goto invalid_format;
		if (s[0] != '"' || s[1] != ')') goto invalid_format;

		encidx = rb_enc_find_index2(encname, (long)size);
		if (encidx < 0) {
		    rb_raise(rb_eRuntimeError, "dumped string has unknown encoding name");
		}
		rb_enc_associate_index(undumped, encidx);
	    }
	    break;
	}

	if (*s == '\\') {
	    s++;
	    if (s >= s_end) {
		rb_raise(rb_eRuntimeError, "invalid escape");
	    }
	    undump_after_backslash(undumped, &s, s_end, &enc, &utf8, &binary);
	}
	else {
	    rb_str_cat(undumped, s++, 1);
	}
    }

    return undumped;
invalid_format:
    rb_raise(rb_eRuntimeError, "invalid dumped string; not wrapped with '\"' nor '\"...\".force_encoding(\"...\")' form");
}

#unicode_normalize(form = :nfc)

Unicode Normalization—Returns a normalized form of str, using Unicode normalizations NFC, NFD, NFKC, or NFKD. The normalization form used is determined by form, which can be any of the four values :nfc, :nfd, :nfkc, or :nfkd. The default is :nfc.

If the string is not in a Unicode Encoding, then an ::Exception is raised. In this context, ‘Unicode Encoding’ means any of UTF-8, UTF-16BE/LE, and UTF-32BE/LE, as well as GB18030, UCS_2BE, and UCS_4BE. Anything other than UTF-8 is implemented by converting to UTF-8, which makes it slower than UTF-8.

"a\u0300".unicode_normalize        #=> "\u00E0"
"a\u0300".unicode_normalize(:nfc)  #=> "\u00E0"
"\u00E0".unicode_normalize(:nfd)   #=> "a\u0300"
"\xE0".force_encoding('ISO-8859-1').unicode_normalize(:nfd)
                                   #=> Encoding::CompatibilityError raised
[ GitHub ]

  
# File 'string.c', line 11207

static VALUE
rb_str_unicode_normalize(int argc, VALUE *argv, VALUE str)
{
    return unicode_normalize_common(argc, argv, str, id_normalize);
}

#unicode_normalize!(form = :nfc)

Destructive version of #unicode_normalize, doing Unicode normalization in place.

[ GitHub ]

  
# File 'string.c', line 11220

static VALUE
rb_str_unicode_normalize_bang(int argc, VALUE *argv, VALUE str)
{
    return rb_str_replace(str, unicode_normalize_common(argc, argv, str, id_normalize));
}

#unicode_normalized?(form = :nfc)

Checks whether str is in Unicode normalization form form, which can be any of the four values :nfc, :nfd, :nfkc, or :nfkd. The default is :nfc.

If the string is not in a Unicode Encoding, then an ::Exception is raised. For details, see #unicode_normalize.

"a\u0300".unicode_normalized?        #=> false
"a\u0300".unicode_normalized?(:nfd)  #=> true
"\u00E0".unicode_normalized?         #=> true
"\u00E0".unicode_normalized?(:nfd)   #=> false
"\xE0".force_encoding('ISO-8859-1').unicode_normalized?
                                     #=> Encoding::CompatibilityError raised
[ GitHub ]

  
# File 'string.c', line 11243

static VALUE
rb_str_unicode_normalized_p(int argc, VALUE *argv, VALUE str)
{
    return unicode_normalize_common(argc, argv, str, id_normalized_p);
}

#unpack(format) ⇒ Array #unpack(format, offset: anInteger) ⇒ 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 (“_”) or exclamation mark (“!”) 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 #unpack1, 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.

Integer       |         |
Directive     | Returns | Meaning
------------------------------------------------------------------
C             | Integer | 8-bit unsigned (unsigned char)
S             | Integer | 16-bit unsigned, native endian (uint16_t)
L             | Integer | 32-bit unsigned, native endian (uint32_t)
Q             | Integer | 64-bit unsigned, native endian (uint64_t)
J             | Integer | pointer width unsigned, native endian (uintptr_t)
              |         |
c             | Integer | 8-bit signed (signed char)
s             | Integer | 16-bit signed, native endian (int16_t)
l             | Integer | 32-bit signed, native endian (int32_t)
q             | Integer | 64-bit signed, native endian (int64_t)
j             | Integer | pointer width signed, native endian (intptr_t)
              |         |
S_ S!         | Integer | unsigned short, native endian
I I_ I!       | Integer | unsigned int, native endian
L_ L!         | Integer | unsigned long, native endian
Q_ Q!         | Integer | unsigned long long, native endian (ArgumentError
              |         | if the platform has no long long type.)
J!            | Integer | uintptr_t, native endian (same with J)
              |         |
s_ s!         | Integer | signed short, native endian
i i_ i!       | Integer | signed int, native endian
l_ l!         | Integer | signed long, native endian
q_ q!         | Integer | signed long long, native endian (ArgumentError
              |         | if the platform has no long long type.)
j!            | Integer | intptr_t, native endian (same with j)
              |         |
S> s> S!> s!> | Integer | same as the directives without ">" except
L> l> L!> l!> |         | big endian
I!> i!>       |         |
Q> q> Q!> q!> |         | "S>" is the same as "n"
J> j> J!> j!> |         | "L>" is the same as "N"
              |         |
S< s< S!< s!< | Integer | same as the directives without "<" except
L< l< L!< l!< |         | little endian
I!< i!<       |         |
Q< q< Q!< q!< |         | "S<" is the same as "v"
J< j< J!< j!< |         | "L<" is the same as "V"
              |         |
n             | Integer | 16-bit unsigned, network (big-endian) byte order
N             | Integer | 32-bit unsigned, network (big-endian) byte order
v             | Integer | 16-bit unsigned, VAX (little-endian) byte order
V             | Integer | 32-bit unsigned, VAX (little-endian) byte order
              |         |
U             | Integer | UTF-8 character
w             | Integer | BER-compressed integer (see Array#pack)

Float        |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
D d          | Float   | double-precision, native format
F f          | Float   | single-precision, native format
E            | Float   | double-precision, little-endian byte order
e            | Float   | single-precision, little-endian byte order
G            | Float   | double-precision, network (big-endian) byte order
g            | Float   | single-precision, network (big-endian) byte order

String       |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
A            | String  | arbitrary binary string (remove trailing nulls and ASCII spaces)
a            | String  | arbitrary binary string
Z            | String  | null-terminated string
B            | String  | bit string (MSB first)
b            | String  | bit string (LSB first)
H            | String  | hex string (high nibble first)
h            | String  | hex string (low nibble first)
u            | String  | UU-encoded string
M            | String  | quoted-printable, MIME encoding (see RFC2045)
m            | String  | base64 encoded string (RFC 2045) (default)
             |         | base64 encoded string (RFC 4648) if followed by 0
P            | String  | pointer to a structure (fixed-length string)
p            | String  | pointer to a null-terminated string

Misc.        |         |
Directive    | Returns | Meaning
-----------------------------------------------------------------
@            | ---     | skip to the offset given by the length argument
X            | ---     | skip backward one byte
x            | ---     | skip forward one byte

The keyword offset can be given to start the decoding after skipping the specified amount of bytes:

"abc".unpack("C*") # => [97, 98, 99]
"abc".unpack("C*", offset: 2) # => [99]
"abc".unpack("C*", offset: 4) # => offset outside of string (ArgumentError)

HISTORY

  • J, J! j, and j! are available since Ruby 2.3.

  • Q_, Q!, q_, and q! are available since Ruby 2.1.

  • I!<, i!<, I!>, and i!> are available since Ruby 1.9.3.

[ GitHub ]

  
# File 'pack.rb', line 275

def unpack(fmt, offset: 0)
  Primitive.pack_unpack(fmt, offset)
end

#unpack1(format) ⇒ Object #unpack1(format, offset: anInteger) ⇒ Object

Decodes str (which may contain binary data) according to the format string, returning the first value extracted.

See also #unpack, Array#pack.

Contrast with #unpack:

"abc \0\0abc \0\0".unpack('A6Z6')   #=> ["abc", "abc "]
"abc \0\0abc \0\0".unpack1('A6Z6')  #=> "abc"

In that case data would be lost but often it’s the case that the array only holds one value, especially when unpacking binary data. For instance:

"\xff\x00\x00\x00".unpack("l")         #=>  [255]
"\xff\x00\x00\x00".unpack1("l")        #=>  255

Thus unpack1 is convenient, makes clear the intention and signals the expected return value to those reading the code.

The keyword offset can be given to start the decoding after skipping the specified amount of bytes:

"abc".unpack1("C*") # => 97
"abc".unpack1("C*", offset: 2) # => 99
"abc".unpack1("C*", offset: 4) # => offset outside of string (ArgumentError)
[ GitHub ]

  
# File 'pack.rb', line 308

def unpack1(fmt, offset: 0)
  Primitive.pack_unpack1(fmt, offset)
end

#upcase(*options) ⇒ String

Returns a string containing the upcased characters in self:

s = 'Hello World!' # => "Hello World!"
s.upcase           # => "HELLO WORLD!"

The casing may be affected by the given options; see Case Mapping.

Related: #upcase!, #downcase, #downcase!.

[ GitHub ]

  
# File 'string.c', line 7237

static VALUE
rb_str_upcase(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_UPCASE;
    VALUE ret;

    flags = check_case_options(argc, argv, flags);
    enc = str_true_enc(str);
    if (case_option_single_p(flags, enc, str)) {
        ret = rb_str_new(RSTRING_PTR(str), RSTRING_LEN(str));
        str_enc_copy(ret, str);
        upcase_single(ret);
    }
    else if (flags&ONIGENC_CASE_ASCII_ONLY) {
        ret = rb_str_new(0, RSTRING_LEN(str));
        rb_str_ascii_casemap(str, ret, &flags, enc);
    }
    else {
        ret = rb_str_casemap(str, &flags, enc);
    }

    return ret;
}

#upcase!(*options) ⇒ self?

Upcases the characters in self; returns self if any changes were made, nil otherwise:

s = 'Hello World!' # => "Hello World!"
s.upcase!          # => "HELLO WORLD!"
s                  # => "HELLO WORLD!"
s.upcase!          # => nil

The casing may be affected by the given options; see Case Mapping.

Related: #upcase, #downcase, #downcase!.

[ GitHub ]

  
# File 'string.c', line 7198

static VALUE
rb_str_upcase_bang(int argc, VALUE *argv, VALUE str)
{
    rb_encoding *enc;
    OnigCaseFoldType flags = ONIGENC_CASE_UPCASE;

    flags = check_case_options(argc, argv, flags);
    str_modify_keep_cr(str);
    enc = str_true_enc(str);
    if (case_option_single_p(flags, enc, str)) {
        if (upcase_single(str))
            flags |= ONIGENC_CASE_MODIFIED;
    }
    else if (flags&ONIGENC_CASE_ASCII_ONLY)
        rb_str_ascii_casemap(str, str, &flags, enc);
    else
	str_shared_replace(str, rb_str_casemap(str, &flags, enc));

    if (ONIGENC_CASE_MODIFIED&flags) return str;
    return Qnil;
}

#upto(other_string, exclusive = false) {|string| ... } ⇒ self #upto(other_string, exclusive = false) ⇒ Enumerator

With a block given, calls the block with each String value returned by successive calls to String#succ; the first value is self, the next is self.succ, and so on; the sequence terminates when value other_string is reached; returns self:

'a8'.upto('b6') {|s| print s, ' ' } # => "a8"

Output:

a8 a9 b0 b1 b2 b3 b4 b5 b6

If argument exclusive is given as a truthy object, the last value is omitted:

'a8'.upto('b6', true) {|s| print s, ' ' } # => "a8"

Output:

a8 a9 b0 b1 b2 b3 b4 b5

If other_string would not be reached, does not call the block:

'25'.upto('5') {|s| fail s }
'aa'.upto('a') {|s| fail s }

With no block given, returns a new Enumerator:

'a8'.upto('b6') # => #<Enumerator: "a8":upto("b6")>
[ GitHub ]

  
# File 'string.c', line 4729

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

    rb_scan_args(argc, argv, "11", &end, &exclusive);
    RETURN_ENUMERATOR(beg, argc, argv);
    return rb_str_upto_each(beg, end, RTEST(exclusive), str_upto_i, Qnil);
}