Ruby Wiki
Advertisement

String is the class of all string objects. Strings are stored as sequences of bytes.

Inherits: Object.

Mixins: Comparable, Enumerable.

Methods[]

Except as noted, methods that do string comparisons can be made case-insensitive, at least for ASCII letters, by setting $= to a true value. This feature is deprecated in Ruby 1.8, and has been removed from Ruby 1.9. Use casecmp instead.

Method Parameters Description
== 1 Returns true if the left and right strings are equal.
> 1 Returns true if self is greater than the parameter, based on the <=> operator.
>= 1 Returns true if self is greater than or equal to the parameter, based on the <=> operator.
< 1 Returns true if self is less than the parameter, based on the <=> operator.
<= 1 Returns true if self is less than or equal to the parameter, based on the <=> operator.
<=> 1 "Spaceship operator": returns -1 if the left parameter is less than the right, 0 if equal, +1 if greater.
+ 1 Concatenation operator: returns the concatenation of the two strings.
* 1 Duplication operator: the right operator is an Integer and must be at least zero. The right operand gives the number of copies of the left operand to make. The return value is the concatenation of those copies.
% 1 Format operator: the left operator contains format specifiers in a printf-like syntax. If there is one format specifier, the right operator may be of any type that matches it. If there are two or more, the right operand is an Array containing values that match them.
[] 1 or 2 Subscript operator: there are three ways to arrange the parameters:
  • One parameter: an Integer, Range, String, or Regexp. A String or a Regexp returns the first substring that matches, or nil if no match.
  • Two parameters: two Integers, an index and a length.
  • Two parameters: a Regexp and an Integer. If the Integer is zero, it takes the whole match; if greater, it takes the numbered match group.
[]= 2 or 3 Subscript and assign: the first and possibly second parameters are as for [], and the last is inserted in place of the indexed subtring.
=~ 1 If the right operator is a Regexp, returns the position of the first match, or nil if no match. Otherwise, converts into other =~ self, which usually returns nil. If the right operator is a String, a TypeError results.
<< 1 self << other has the same meaning as self.concat(other).
all? 0 plus block Passes each element to a given block and returns true if the block returns a true value for all of them.
any? 0 plus block Passes each element to a given block and returns true if the block returns a true value for at least one of them.
between? 2 self.between(min, max) returns true if self is not less than min and not greater than max. The limits are part of the range, so "cat".between?("cat", "dog") returns true.
capitalize 0 Returns the string with the first character converted to uppercase if it is a letter, and all other letters converted to lowercase.
capitalize! 0 As capitalize, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
casecmp 1 self.casecmp(other) behaves like <=>, but compares the strings converted to lowercase.
center 1 or 2 self.center(width[, pad]) pads the string with spaces on both ends, leaving the original string centered in the final string. If pad is provided, it must not be an empty string and is used instead of a space.
chomp 0 or 1 self.chomp(separator) removes the string separator from the end of the string, if the separator is found there. If no separator is given, the special variable $/ is used; if this has not been changed, chomp will remove any of \n, \r, or \r\n.
chomp! 0 or 1 As chomp, but replaces the string with the result. Returns the modified string, or nil if no change was made.
chop 0 Returns a copy of the string with the last character removed. If the string ends with \r\n, both characters are removed. "".chop returns "".
chop! 0 As chop, but replaces the string with the result.
collect 0 plus block self.collect block returns an array containing the results of running the block once for each element of self.
concat 1 self.concat(other) converts other to a String, appends it to self (which is thus modified), and returns the result. If other is a Fixnum between 0 and 255 inclusive, it is converted to a single-character string.
count 1 or more Parameters are strings interpreted as sets of characters as for tr. count returns the number of characters in the string that occur in all of these sets.
crypt 1 self.crypt(salt) uses the POSIX function crypt to scramble the string. salt should be two characters long, each character from [a-zA-Z0-9./]. Note that crypt is not especially secure.
delete 1 or more Parameters are strings interpreted as sets of characters as for count or tr. delete returns a String in which any characters found in all of these sets are deleted.
delete! 1 or more As delete, but replaces the string with the result. Returns the string, or nil if it was not modified.
detect 0 or 1, plus block Synonym for find.
downcase 0 Returns the string with all letters converted to lowercase.
downcase! 0 As downcase, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
dump 0 Converts self into an escaped form using "\xXX" for non-printable characters. Different from inspect in that it uses bytes rather than code points when a multibyte character set is in effect.
each 0 or 1, plus block Synonym for each_line.
each_byte 0 plus block Passes each byte in the string to the given block.
each_line 0 or 1, plus block Splits the string using the supplied parameter as a record separator and calls the block once with each resulting record. If there is no parameter, the special variable $/ is used. If the record separator is an empty string, the string is split on any \n characters and multiple consecutive newlines are appended together.
each_with_index 0 plus block Calls a given block with two parameters, the item and its index, for each item in self.
empty? 0 Returns true if self has length 0.
entries 0 Synonym for to_a.
eql? 1 self.eql?(other) returns true if the two strings are equal. It is different from == in that eql does not attempt to convert the right operand.
find 0 or 1, plus block self.find(ifnone) block passes each element of self to the block and returns the first for which the block does not return false or nil. If no object matches, ifnone is called and its return value is the return value of find. ifnone may be omitted, in which case find returns nil on no match.
find_all 0 plus block self.find_all block passes each element of self to the block and returns an array of all elements for which the block returns a true value. reject has the opposite sense to find_all.
grep 1 plus optional block self.grep(pattern) returns every element in self for which the pattern matches (that is, pattern === element. A block may be given, in which case matching elements will be passed to it and the return values stored in the output array.
gsub 1+block or 2 self.gsub(pattern, subst) returns a copy of self in which all matches for pattern are replaced by subst. pattern may be a String or a Regexp.

If subst is omitted, a block must be provided; the block receives each match and returns the string that will be substituted for it.

To substitute only the first match, use sub.

gsub! 1+block or 2 As gsub, but replaces the string with the result. Returns the string.
hash 0 Returns a hash code for use in a Hash object.
hex 0 Returns an Integer for which the string is a hexadecimal representation. The string can have a leading minus sign. The conversion ends on any invalid character.
include? 1 self.include?(other) returns true if other is included within self.
index 1 or 2 self.index(other) returns the index of the first substring of self that is equal to other, or nil if no match.

self.index(other, start) returns the first such index that is not less than start, or nil if no match.

inject 0 or 1, plus block self.inject(initial) block calls the block once for each element of self. It calls the block as block(memo, obj) where obj is the current element of self, and memo is set to initial on the first call and to the last return value of the block on subsequent calls. initial may be omitted, and will be taken as nil.
insert 2 self.insert(index, other) inserts other into self such that other begins at the index.
inspect 0 Converts self into an escaped form using "\xXX" for non-printable characters. Different from dump in that it uses code points rather than bytes when a multibyte character set is in effect.
intern 0 Returns the Symbol corresponding to str, creating the symbol if it did not previously exist.
length 0 Returns the length of the string.
ljust 1 or 2 self.ljust(width[, pad]) pads the string with spaces to the right, leaving the original string left justified in the final string. If pad is provided, it must not be an empty string and is used instead of a space.
lstrip 0 Returns a copy of the string with whitespace removed from the start.
lstrip! 0 As lstrip, but replaces the string with the result. Returns the string, or nil if no changes were made.
map 0 Synonym for collect.
match 1 self.match(other) converts other to a Regexp and then calls regexp.match(self).
max 0 plus optional block Returns the element with the maximum value, according to the elements's comparison operators or to an optional block which behaves like a <=> operator.
member? 1 self.member?(obj) returns true if any member of self equals obj, according to the == operator.
min 0 plus optional block Returns the element with the minimum value, according to the elements's comparison operators or to an optional block which behaves like a <=> operator.
next 0 Synonym for succ.
next! 0 Synonym for succ!.
oct 0 Returns an Integer for which the string is an octal representation. The string can have a leading minus sign. The conversion ends on any invalid character.
partition 0 plus block self.partition block returns an array of two arrays, of which the first contains the elements for which the block returned a true value, and the second contains the rest. Equivalent to [ self.find_all block, self.rejectblock ] except that self is scanned only once.
reject 0 plus block self.reject block passes each element of self to the block and returns an array of all elements for which the block returns a false value. find_all has the opposite sense to reject.
replace 1 self.replace(other) replaces self with the contents and taint status of other.
reverse 0 Returns the string with the order of the bytes reversed.
reverse! 0 As reverse, but replaces the string with the result. Always returns the replaced string.
rindex 1 or 2 self.rindex(other) returns the index of the last substring of self that is equal to other, or nil if no match.

self.rindex(other, start) returns the last such index only if it is not less than start, or nil if no match.

rjust 1 or 2 self.rjust(width[, pad]) pads the string with spaces to the left, leaving the original string right justified in the final string. If pad is provided, it must not be an empty string and is used instead of a space.
rstrip 0 Returns a copy of the string with whitespace removed from the end.
rstrip! 0 As rstrip, but replaces the string with the result. Returns the string, or nil if no changes were made.
scan 1 plus optional block str.scan(pattern) looks for all matches to pattern and returns an Array containing each match. If the pattern is a Regexp and contains groups, each match is an Array containing the matched groups; otherwise, each match is a String.

If a block is provided, the matches are passed to the block, which returns a String; the concatenation of the Strings is the return value from scan.

select 0 Synonym for find_all.
size 0 Synonym for length.
slice 1 or 2 self.slice(index) is equivalent to self[index]. self.slice(p1, p2) is equivalent to self[p1, p2].
slice! 1 or 2 As slice, but replaces the string with the result.
sort 0 plus optional block Returns an Array containing the elements of self, sorted according to a passed block if there is one, or self's <=> operator otherwise. The block should return -1, 0, or +1 to indicate that the first parameter is less than, equal to, or greater than the second.
sort_by 0 plus optional block Returns an Array containing the elements of self, sorted according to a key returned by a passed block. The block takes one parameter, an element of self, and returns a key whose comparison will sort the returned array.
split 0, 1, or 2 self.split([pattern[, limit]]) splits self into pieces bounded by the pattern, which may be a String or a Regexp. If pattern is a single space, split divides the string at any whitespace. If pattern is not specified, the special variable $; is used; if this is nil (which is the default), the string is split on whitespace. The split strings are returned as an Array.

If the limit is not given, no empty strings will be returned at the end of the list. If limit is positive, at most that many strings will be returned; the last will have any remaining portion of the input string. If limit is zero or negative, all strings are returned, including empty ones at the end.

squeeze 0 or more Parameters are strings interpreted as sets of characters as for tr. count returns the string with duplicate runs of characters found in all of the sets removed. If there are no parameters, all characters are squeezed.
squeeze! 0 or more As squeeze, but replaces the string with the result. Returns the modified string, or nil if no modifications were made.
strip 0 Returns a copy of the string with whitespace removed from the start and the end.
strip! 0 As strip, but replaces the string with the result. Returns the string, or nil if no changes were made.
sub 1+block or 2 self.sub(pattern, subst) returns a copy of self in which the first match for pattern is replaced by subst. pattern may be a String or a Regexp.

If subst is omitted, a block must be provided; the block receives the first match and returns the string that will be substituted for it.

To substitute all matches, use gsub.

sub! 1+block or 2 As sub, but replaces the string with the result. Returns the string.
succ 0 "Increments" the string, advancing the last character to the next one in the collating sequence, but keeping uppercase uppercase, lowercase lowercase, digits digits, and non-alphanumerics non-alphanumerics. If a range is exceeded, the character is reset to the start, and a "carry" propagates to the left.
succ! 0 As succ, but replaces the string with the result.
sum 0 or 1 self.sum(n) returns a basic n-bit checksum of the string, being the sum of the binary values of the bytes modulo 2n-1. If n is not given, 16 is used.
swapcase 0 Returns the string with the cases of all letters reversed.
swapcase! 0 As swapcase, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
to_a 0 Returns an Array containing the elements of self.
to_f 0 Returns self converted to a Float. Conversion ends at an invalid character.
to_i 0 or 1 Returns self converted to an Integer. The optional parameter is an Integer giving the radix for the conversion; the radix is 10 if this is not present or if it is zero. Conversion ends at an invalid character.
to_s 0 Returns self unchanged.
to_str 0 Synonym for to_s.
to_sym 0 Synonym for intern.
tr 2 self.tr(from_str, to_str) returns a copy of the string in which characters in the from_str are replaced with characters in the same position in the to_str. Either string may use c1-c2 notation to denote ranges, and from_str may start with ^ to mean all characters except those listed.
tr! 2 As tr, but replaces the string with the result. Returns the string if it was modified, else nil.
tr_s 2 Processes the string as tr and removes duplicate characters from replaced regions of the string.
tr_s! 2 As tr_s, but replaces the string with the result. Returns the string if it was modified, else nil.
upcase 0 Returns the string with all letters converted to uppercase.
upcase! 0 As upcase, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
upto 1 plus block self.upto(other) block calls the block, first with self and then with the succeeding results of succ, until other is reached and passed to the last call to the block.
zip 0 or more, plus block Converts all parameters to arrays. Then, for each index of self, forms an array whose first element is self[index] and each subsequent element is drawn from the parameters at the same index. If a block is given, this array is passed to it and the return value substituted for the array. Finally, the arrays or block returns are placed into a new array, at the same indexes from which the elements of self were drawn.

If a parameter is longer than self, the extra elements are ignored; if shorter, the missing elements are replaced by nil.

New in Ruby 1.9[]

$= no longer makes string comparisons case-insensitive in Ruby 1.9.

Method Parameters Description
ascii_only? 0 Returns true if the string contains no non-ASCII bytes (bytes with the eight bit set).
bytes 0 Synonym for each_byte.
bytesize 0 Returns the length of the string in bytes, regardless of any multibyte encoding that may be in effect.
chr 0 self.chr eturns a one-byte string containing the first byte of self, or an empty string if self is empty.
clear 0 Makes the string empty.
each 0 or 1, plus block Synonym for each_line.
each_char 0 plus block Passes each (possibly multibyte) character in the string to the given block.
encoding 0 Returns the Encoding that applies to the String.
end_with? 0 or more The parameters are Strings; end_with? returns true if the given string ends with any of the parameters. It returns false if there are no parameters.
force_encoding 1 Sets the encoding to the parameter, an Encoding object or a String that names an encoding, and returns the string.
length 0 If a multibyte encoding is in effect, length returns the number of characters rather than bytes. To get the number of bytes, use bytesize.
lines 0 Synonym for each_line.
ord 0 Returns the Integer code point of the first character of the string, taking any encoding into account. If the string is empty, ArgumentError results.
partition 1 self.partition(sep) searches for the first ocurrence of sep; if sep is found, it returns an Array containing the part of the string before sep, sep itself, and the part after sep. If sep is not found, the Array is [ self, "", "" ].
rpartition 1 self.rpartition(sep) searches for the last ocurrence of sep; if sep is found, it returns an Array containing the part of the string before sep, sep itself, and the part after sep. If sep is not found, the Array is [ self, "", "" ].
start_with? 0 or more The parameters are Strings; start_with? returns true if the given string begins with any of the parameters. It returns false if there are no parameters.
try_convert 1 This is a singleton method. String.try_convert(obj) tries to convert obj to a String, using its to_str It returns the String, or nil if the conversion fails.
valid_encoding? 0 Returns true if the string is validly encoded in its current Encoding.
Advertisement