A String object holds and manipulates an arbitrary sequence of bytes, typically representing characters. String objects may be created using String::new or as literals.
Because of aliasing issues, users of strings should be aware of the methods that modify the contents of a String object. Typically, methods with names ending in ``!’’ modify their receiver, while those without a ``!’’ return a new String. However, there are exceptions, such as String#[]=.
| Public Methods | |
|---|---|
| % | Format—Uses str as a format specification, and returns the result of applying it to arg. If the format specification contains more than one substitution, then arg must be an Array containing the values to be substituted. See Kernel::sprintf for details of the format string. |
| * | Copy—Returns a new String containing integer copies of the receiver. |
| + | Concatenation—Returns a new String containing other_str concatenated to str. |
| << | Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation. |
| <=> | Comparison—Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater than str. If the strings are of different lengths, and the strings are equal when compared up to the shortest length, then the longer string is considered greater than the shorter one. If the variable $= is false, the comparison is based on comparing the binary values of each character in the string. In older versions of Ruby, setting $= allowed case-insensitive comparisons; this is now deprecated in favor of using String#casecmp. |
| == | Equality—If obj is not a String, returns false. Otherwise, returns true if str <=> obj returns zero. |
| =~ | Match—If obj is a Regexp, use it as a pattern to match against str,and returns the position the match starts, or nil if there is no match. Otherwise, invokes obj.=~, passing str as an argument. The default =~ in Object returns false. |
| [] | Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end. |
| []= | Element Assignment—Replaces some or all of the content of str. The portion of the string affected is determined using the same criteria as String#[]. If the replacement string is not the same length as the text it is replacing, the string will be adjusted accordingly. If the regular expression or string is used as the index doesn’t match a position in the string, IndexError is raised. If the regular expression form is used, the optional second Fixnum allows you to specify which portion of the match to replace (effectively using the MatchData indexing rules. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment. |
| capitalize | Returns a copy of str with the first character converted to uppercase and the remainder to lowercase. |
| capitalize! | Modifies str by converting the first character to uppercase and the remainder to lowercase. Returns nil if no changes are made. |
| casecmp | Case-insensitive version of String#<=>. |
| center | If integer is greater than the length of str, returns a new String of length integer with str centered and padded with padstr; otherwise, returns str. |
| chomp | 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). |
| chomp! | Modifies str in place as described for String#chomp, returning str, or nil if no modifications were made. |
| chop | Returns a new String with the last character removed. If the string ends with \r\n, both characters are removed. Applying chop to an empty string returns an empty string. String#chomp is often a safer alternative, as it leaves the string unchanged if it doesn’t end in a record separator. |
| chop! | Processes str as for String#chop, returning str, or nil if str is the empty string. See also String#chomp!. |
| concat | Append—Concatenates the given object to str. If the object is a Fixnum between 0 and 255, it is converted to a character before concatenation. |
| count | 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. |
| crypt | Applies a one-way cryptographic hash to str by invoking the standard library function crypt. The argument is the salt string, which should be two characters long, each character drawn from [a-zA-Z0-9./]. |
| delete | Returns a copy of str with all characters in the intersection of its arguments deleted. Uses the same rules for building the set of characters as String#count. |
| delete! | Performs a delete operation in place, returning str, or nil if str was not modified. |
| downcase | Returns a copy of str with all uppercase letters replaced with their lowercase counterparts. The operation is locale insensitive—only characters ``A’’ to ``Z’’ are affected. |
| downcase! | Downcases the contents of str, returning nil if no changes were made. |
| dump | Produces a version of str with all nonprinting characters replaced by \nnn notation and all special characters escaped. |
| each | Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together. |
| each_ |
Passes each byte in str to the given block. |
| each_ |
Splits str using the supplied parameter as the record separator ($/ by default), passing each substring in turn to the supplied block. If a zero-length record separator is supplied, the string is split on \n characters, except that multiple successive newlines are appended together. |
| empty? | Returns true if str has a length of zero. |
| eql? | Two strings are equal if the have the same length and content. |
| gsub | Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but ’\d’ will match a backslash followed by a ‘d’). |
| gsub! | Performs the substitutions of String#gsub in place, returning str, or nil if no substitutions were performed. |
| hash | Return a hash based on the string’s length and content. |
| hex | 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. |
| include? | Returns true if str contains the given string or character. |
| index | Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search. |
| initialize_ |
Replaces the contents and taintedness of str with the corresponding values in other_str. |
| insert | Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is insert aString so that it starts at the given index. |
| inspect | Returns a printable version of str, with special characters escaped. |
| intern | Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name. |
| length | Returns the length of str. |
| ljust | 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. |
| lstrip | Returns a copy of str with leading whitespace removed. See also String#rstrip and String#strip. |
| lstrip! | Removes leading whitespace from str, returning nil if no change was made. See also String#rstrip! and String#strip!. |
| match | Converts pattern to a Regexp (if it isn’t already one), then invokes its match method on str. |
| new | Returns a new string object containing a copy of str. |
| next | Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set’s collating sequence. |
| next! | Equivalent to String#succ, but modifies the receiver in place. |
| oct | 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. |
| replace | Replaces the contents and taintedness of str with the corresponding values in other_str. |
| reverse | Returns a new string with the characters from str in reverse order. |
| reverse! | Reverses str in place. |
| rindex | Returns the index of the last occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to end the search—characters beyond this point will not be considered. |
| rjust | 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. |
| rstrip | Returns a copy of str with trailing whitespace removed. See also String#lstrip and String#strip. |
| rstrip! | Removes trailing whitespace from str, returning nil if no change was made. See also String#lstrip! and String#strip!. |
| scan | 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. |
| size | Returns the length of str. |
| slice | Element Reference—If passed a single Fixnum, returns the code of the character at that position. If passed two Fixnum objects, returns a substring starting at the offset given by the first, and a length given by the second. If given a range, a substring containing characters at offsets given by the range is returned. In all three cases, if an offset is negative, it is counted from the end of str. Returns nil if the initial offset falls outside the string, the length is negative, or the beginning of the range is greater than the end. |
| slice! | Deletes the specified portion from str, and returns the portion deleted. The forms that take a Fixnum will raise an IndexError if the value is out of range; the Range form will raise a RangeError, and the Regexp and String forms will silently ignore the assignment. |
| split | Divides str into substrings based on a delimiter, returning an array of these substrings. |
| squeeze | Builds a set of characters from the other_str parameter(s) using the procedure described for String#count. Returns a new string where runs of the same character that occur in this set are replaced by a single character. If no arguments are given, all runs of identical characters are replaced by a single character. |
| squeeze! | Squeezes str in place, returning either str, or nil if no changes were made. |
| strip | Returns a copy of str with leading and trailing whitespace removed. |
| strip! | Removes leading and trailing whitespace from str. Returns nil if str was not altered. |
| sub | Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block. The pattern will typically be a Regexp; if it is a String then no regular expression metacharacters will be interpreted (that is /\d/ will match a digit, but ’\d’ will match a backslash followed by a ‘d’). |
| sub! | Performs the substitutions of String#sub in place, returning str, or nil if no substitutions were performed. |
| succ | Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set’s collating sequence. |
| succ! | Equivalent to String#succ, but modifies the receiver in place. |
| sum | Returns a basic n-bit checksum of the characters in str, where n is the optional Fixnum parameter, defaulting to 16. The result is simply the sum of the binary value of each character in str modulo 2n - 1. This is not a particularly good checksum. |
| swapcase | Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase. |
| swapcase! | Equivalent to String#swapcase, but modifies the receiver in place, returning str, or nil if no changes were made. |
| to_ |
Returns the result of interpreting leading characters in str as a floating point number. Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0.0 is returned. This method never raises an exception. |
| to_ |
Returns the result of interpreting leading characters in str as an integer base base (2, 8, 10, or 16). Extraneous characters past the end of a valid number are ignored. If there is not a valid number at the start of str, 0 is returned. This method never raises an exception. |
| to_ |
Returns the receiver. |
| to_ |
Returns the receiver. |
| to_ |
Returns the Symbol corresponding to str, creating the symbol if it did not previously exist. See Symbol#id2name. |
| tr | Returns a copy of str with the characters in from_str replaced by the corresponding characters in to_str. If to_str is shorter than from_str, it is padded with its last character. Both strings may use the c1—c2 notation to denote ranges of characters, and from_str may start with a ^, which denotes all characters except those listed. |
| tr! | Translates str in place, using the same rules as String#tr. Returns str, or nil if no changes were made. |
| tr_ |
Processes a copy of str as described under String#tr, then removes duplicate characters in regions that were affected by the translation. |
| tr_ |
Performs String#tr_s processing on str in place, returning str, or nil if no changes were made. |
| unpack | Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted. The format string consists of a sequence of single-character directives, summarized in the table at the end of this entry. Each directive may be followed by a number, indicating the number of times to repeat with this directive. An asterisk (``*’’) will use up all remaining elements. The directives sSiIlL may each be followed by an underscore (``_’’) to use the underlying platform’s native size for the specified type; otherwise, it uses a platform-independent consistent size. Spaces are ignored in the format string. See also Array#pack. |
| upcase | Returns a copy of str with all lowercase letters replaced with their uppercase counterparts. The operation is locale insensitive—only characters ``a’’ to ``z’’ are affected. |
| upcase! | Upcases the contents of str, returning nil if no changes were made. |
| upto | Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block. The String#succ method is used to generate each value. |
<code/>and<pre/>for code samples.