Fandom

Ruby Wiki

String

26pages on
this wiki
Add New Page
Talk0 Share

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

Inherits: Object.

Mixins: Comparable, Enumerable.

MethodsEdit

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.

MethodParametersDescription
==1Returns true if the left and right strings are equal.
>1Returns true if self is greater than the parameter, based on the <=> operator.
>=1Returns true if self is greater than or equal to the parameter, based on the <=> operator.
<1Returns true if self is less than the parameter, based on the <=> operator.
<=1Returns 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.
+1Concatenation operator: returns the concatenation of the two strings.
*1Duplication 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.
%1Format 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 2Subscript 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 3Subscript and assign: the first and possibly second parameters are as for [], and the last is inserted in place of the indexed subtring.
=~1If 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.
<<1self << other has the same meaning as self.concat(other).
all?0 plus blockPasses each element to a given block and returns true if the block returns a true value for all of them.
any?0 plus blockPasses each element to a given block and returns true if the block returns a true value for at least one of them.
between?2self.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.
capitalize0Returns the string with the first character converted to uppercase if it is a letter, and all other letters converted to lowercase.
capitalize!0As capitalize, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
casecmp1self.casecmp(other) behaves like <=>, but compares the strings converted to lowercase.
center1 or 2self.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.
chomp0 or 1self.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 1As chomp, but replaces the string with the result. Returns the modified string, or nil if no change was made.
chop0Returns a copy of the string with the last character removed. If the string ends with \r\n, both characters are removed. "".chop returns "".
chop!0As chop, but replaces the string with the result.
collect0 plus blockself.collect block returns an array containing the results of running the block once for each element of self.
concat1self.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.
count1 or moreParameters 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.
crypt1self.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.
delete1 or moreParameters 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 moreAs delete, but replaces the string with the result. Returns the string, or nil if it was not modified.
detect0 or 1, plus blockSynonym for find.
downcase0Returns the string with all letters converted to lowercase.
downcase!0As downcase, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
dump0Converts 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.
each0 or 1, plus blockSynonym for each_line.
each_byte0 plus blockPasses each byte in the string to the given block.
each_line0 or 1, plus blockSplits 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_index0 plus blockCalls a given block with two parameters, the item and its index, for each item in self.
empty?0Returns true if self has length 0.
entries0Synonym for to_a.
eql?1self.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.
find0 or 1, plus blockself.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_all0 plus blockself.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.
grep1 plus optional blockself.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.
gsub1+block or 2self.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 2As gsub, but replaces the string with the result. Returns the string.
hash0Returns a hash code for use in a Hash object.
hex0Returns 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?1self.include?(other) returns true if other is included within self.
index1 or 2self.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.

inject0 or 1, plus blockself.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.
insert2self.insert(index, other) inserts other into self such that other begins at the index.
inspect0Converts 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.
intern0Returns the Symbol corresponding to str, creating the symbol if it did not previously exist.
length0Returns the length of the string.
ljust1 or 2self.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.
lstrip0Returns a copy of the string with whitespace removed from the start.
lstrip!0As lstrip, but replaces the string with the result. Returns the string, or nil if no changes were made.
map0Synonym for collect.
match1self.match(other) converts other to a Regexp and then calls regexp.match(self).
max0 plus optional blockReturns the element with the maximum value, according to the elements's comparison operators or to an optional block which behaves like a <=> operator.
member?1self.member?(obj) returns true if any member of <code>self equals obj, according to the == operator.
min0 plus optional blockReturns the element with the minimum value, according to the elements's comparison operators or to an optional block which behaves like a <=> operator.
next0Synonym for succ.
next!0Synonym for succ!.
oct0Returns 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.
partition0 plus blockself.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.
reject0 plus blockself.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.
replace1self.replace(other) replaces self with the contents and taint status of other.
reverse0Returns the string with the order of the bytes reversed.
reverse!0As reverse, but replaces the string with the result. Always returns the replaced string.
rindex1 or 2self.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.

rjust1 or 2self.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.
rstrip0Returns a copy of the string with whitespace removed from the end.
rstrip!0As rstrip, but replaces the string with the result. Returns the string, or nil if no changes were made.
scan1 plus optional blockstr.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.

select0Synonym for find_all.
size0Synonym for length.
slice1 or 2self.slice(index) is equivalent to self[index]. self.slice(p1, p2) is equivalent to self[p1, p2].
slice!1 or 2As slice, but replaces the string with the result.
sort0 plus optional blockReturns 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_by0 plus optional blockReturns 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.
split0, 1, or 2self.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.

squeeze0 or moreParameters 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 moreAs squeeze, but replaces the string with the result. Returns the modified string, or nil if no modifications were made.
strip0Returns a copy of the string with whitespace removed from the start and the end.
strip!0As strip, but replaces the string with the result. Returns the string, or nil if no changes were made.
sub1+block or 2self.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 2As sub, but replaces the string with the result. Returns the string.
succ0"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!0As succ, but replaces the string with the result.
sum0 or 1self.sum(n) returns a basic n-bit checksum of the string, being the sum of the binary values of the bytes modulo <code>2n-1. If n is not given, 16 is used.
swapcase0Returns the string with the cases of all letters reversed.
swapcase!0As swapcase, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
to_a0Returns an Array containing the elements of self.
to_f0Returns self converted to a Float. Conversion ends at an invalid character.
to_i0 or 1Returns 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_s0Returns self unchanged.
to_str0Synonym for to_s.
to_sym0Synonym for intern.
tr2self.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!2As tr, but replaces the string with the result. Returns the string if it was modified, else nil.
tr_s2Processes the string as tr and removes duplicate characters from replaced regions of the string.
tr_s!2As tr_s, but replaces the string with the result. Returns the string if it was modified, else nil.
upcase0Returns the string with all letters converted to uppercase.
upcase!0As upcase, but replaces the string with the result. Returns the replaced string if any changes were made, else nil.
upto1 plus blockself.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.
zip0 or more, plus blockConverts 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.9Edit

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

MethodParametersDescription
ascii_only?0Returns true if the string contains no non-ASCII bytes (bytes with the eight bit set).
bytes0Synonym for each_byte.
bytesize0Returns the length of the string in bytes, regardless of any multibyte encoding that may be in effect.
chr0self.chr eturns a one-byte string containing the first byte of self, or an empty string if self is empty.
clear0Makes the string empty.
each0 or 1, plus blockSynonym for each_line.
each_char0 plus blockPasses each (possibly multibyte) character in the string to the given block.
encoding0Returns the Encoding that applies to the String.
end_with?0 or moreThe 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_encoding1Sets the encoding to the parameter, an Encoding object or a String that names an encoding, and returns the string.
length0If a multibyte encoding is in effect, length returns the number of characters rather than bytes. To get the number of bytes, use bytesize.
lines0Synonym for each_line.
ord0Returns the Integer code point of the first character of the string, taking any encoding into account. If the string is empty, ArgumentError results.
partition1self.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, "", "" ].
rpartition1self.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 moreThe 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_convert1This 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?0Returns true if the string is validly encoded in its current Encoding.

Ad blocker interference detected!


Wikia is a free-to-use site that makes money from advertising. We have a modified experience for viewers using ad blockers

Wikia is not accessible if you’ve made further modifications. Remove the custom ad blocker rule(s) and the page will load as expected.