Class: String
Overview
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#[]=.
Instance Method Summary collapse
-
#%(arg) ⇒ String
Format---Uses str as a format specification, and returns the result of applying it to arg.
-
#*(integer) ⇒ String
Copy---Returns a new
Stringcontaining integer copies of the receiver. -
#+(other_str) ⇒ String
Concatenation---Returns a new
Stringcontaining other_str concatenated to str. -
#<< ⇒ Object
Append---Concatenates the given object to str.
-
#<=>(other_str) ⇒ -1, ...
Comparison---Returns -1 if other_str is less than, 0 if other_str is equal to, and +1 if other_str is greater than str.
-
#==(obj) ⇒ Boolean
Equality---If obj is not a
String, returnsfalse. -
#=~(obj) ⇒ Fixnum?
Match---If obj is a
Regexp, use it as a pattern to match against str,and returns the position the match starts, ornilif there is no match. -
#[] ⇒ Object
Element Reference---If passed a single
Fixnum, returns the code of the character at that position. -
#[]= ⇒ Object
Element Assignment---Replaces some or all of the content of str.
-
#each_byte {|fixnum| ... } ⇒ String
Passes each byte in str to the given block.
-
#length ⇒ Integer
Returns the length of str.
-
#capitalize ⇒ String
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
-
#capitalize! ⇒ String?
Modifies str by converting the first character to uppercase and the remainder to lowercase.
-
#casecmp(other_str) ⇒ -1, ...
Case-insensitive version of
String#<=>. -
#center(integer, padstr) ⇒ String
If integer is greater than the length of str, returns a new
Stringof length integer with str centered and padded with padstr; otherwise, returns str. -
#each_char {|cstr| ... } ⇒ String
Passes each character in str to the given block.
-
#chomp(separator = $/) ⇒ String
Returns a new
Stringwith the given record separator removed from the end of str (if present). -
#chomp!(separator = $/) ⇒ String?
Modifies str in place as described for
String#chomp, returning str, ornilif no modifications were made. -
#chop ⇒ String
Returns a new
Stringwith the last character removed. -
#chop! ⇒ String?
Processes str as for
String#chop, returning str, ornilif str is the empty string. -
#concat ⇒ Object
Append---Concatenates the given object to str.
-
#count([other_str]) ⇒ Fixnum
Each other_str parameter defines a set of characters to count.
-
#crypt(other_str) ⇒ String
Applies a one-way cryptographic hash to str by invoking the standard library function
crypt. -
#delete([other_str]) ⇒ String
Returns a copy of str with all characters in the intersection of its arguments deleted.
-
#delete!([other_str]) ⇒ String?
Performs a
deleteoperation in place, returning str, ornilif str was not modified. -
#downcase ⇒ String
Returns a copy of str with all uppercase letters replaced with their lowercase counterparts.
-
#downcase! ⇒ String?
Downcases the contents of str, returning
nilif no changes were made. -
#dump ⇒ String
Produces a version of str with all nonprinting characters replaced by
\nnnnotation and all special characters escaped. -
#each ⇒ Object
Splits str using the supplied parameter as the record separator (
$/by default), passing each substring in turn to the supplied block. -
#each_byte {|fixnum| ... } ⇒ String
Passes each byte in str to the given block.
-
#each_char {|cstr| ... } ⇒ String
Passes each character in str to the given block.
-
#each_line ⇒ Object
Splits str using the supplied parameter as the record separator (
$/by default), passing each substring in turn to the supplied block. -
#empty? ⇒ Boolean
Returns
trueif str has a length of zero. -
#end_with?([suffix]) ⇒ Boolean
Returns true if str ends with the suffix given.
-
#eql?(other) ⇒ Boolean
Two strings are equal if the have the same length and content.
-
#gsub ⇒ Object
Returns a copy of str with all occurrences of pattern replaced with either replacement or the value of the block.
-
#gsub! ⇒ Object
Performs the substitutions of
String#gsubin place, returning str, ornilif no substitutions were performed. -
#hash ⇒ Fixnum
Return a hash based on the string's length and content.
-
#hex ⇒ Integer
Treats leading characters from str as a string of hexadecimal digits (with an optional sign and an optional
0x) and returns the corresponding number. -
#include? ⇒ Object
Returns
trueif str contains the given string or character. -
#index ⇒ Object
Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str.
-
#new(str = "") ⇒ String
constructor
Returns a new string object containing a copy of str.
-
#replace(other_str) ⇒ String
Replaces the contents and taintedness of str with the corresponding values in other_str.
-
#insert(index, other_str) ⇒ String
Inserts other_str before the character at the given index, modifying str.
-
#inspect ⇒ String
Returns a printable version of str, with special characters escaped.
-
#intern ⇒ Object
Returns the
Symbolcorresponding to str, creating the symbol if it did not previously exist. -
#length ⇒ Integer
Returns the length of str.
-
#lines ⇒ Object
Splits str using the supplied parameter as the record separator (
$/by default), passing each substring in turn to the supplied block. -
#ljust(integer, padstr = ' ') ⇒ String
If integer is greater than the length of str, returns a new
Stringof length integer with str left justified and padded with padstr; otherwise, returns str. -
#lstrip ⇒ String
Returns a copy of str with leading whitespace removed.
-
#lstrip! ⇒ self?
Removes leading whitespace from str, returning
nilif no change was made. -
#match(pattern) ⇒ MatchData?
Converts pattern to a
Regexp(if it isn't already one), then invokes itsmatchmethod on str. -
#next ⇒ Object
Returns the successor to str.
-
#next! ⇒ Object
Equivalent to
String#succ, but modifies the receiver in place. -
#oct ⇒ Integer
Treats leading characters of str as a string of octal digits (with an optional sign) and returns the corresponding number.
-
#partition(sep) ⇒ Array
Searches the string for sep and returns the part before it, the sep, and the part after it.
-
#replace(other_str) ⇒ String
Replaces the contents and taintedness of str with the corresponding values in other_str.
-
#reverse ⇒ String
Returns a new string with the characters from str in reverse order.
-
#reverse! ⇒ String
Reverses str in place.
-
#rindex ⇒ Object
Returns the index of the last occurrence of the given substring, character (fixnum), or pattern (regexp) in str.
-
#rjust(integer, padstr = ' ') ⇒ String
If integer is greater than the length of str, returns a new
Stringof length integer with str right justified and padded with padstr; otherwise, returns str. -
#rpartition(sep) ⇒ Array
Searches sep in the string from the end of the string, and returns the part before it, the sep, and the part after it.
-
#rstrip ⇒ String
Returns a copy of str with trailing whitespace removed.
-
#rstrip! ⇒ self?
Removes trailing whitespace from str, returning
nilif no change was made. -
#scan ⇒ Object
Both forms iterate through str, matching the pattern (which may be a
Regexpor aString). -
#length ⇒ Integer
Returns the length of str.
-
#slice ⇒ Object
Element Reference---If passed a single
Fixnum, returns the code of the character at that position. -
#slice! ⇒ Object
Deletes the specified portion from str, and returns the portion deleted.
-
#split(pattern = $;, [limit]) ⇒ Array
Divides str into substrings based on a delimiter, returning an array of these substrings.
-
#squeeze([other_str]) ⇒ String
Builds a set of characters from the other_str parameter(s) using the procedure described for
String#count. -
#squeeze!([other_str]) ⇒ String?
Squeezes str in place, returning either str, or
nilif no changes were made. -
#start_with?([prefix]) ⇒ Boolean
Returns true if str starts with the prefix given.
-
#strip ⇒ String
Returns a copy of str with leading and trailing whitespace removed.
-
#strip! ⇒ String?
Removes leading and trailing whitespace from str.
-
#sub ⇒ Object
Returns a copy of str with the first occurrence of pattern replaced with either replacement or the value of the block.
-
#sub! ⇒ Object
Performs the substitutions of
String#subin place, returning str, ornilif no substitutions were performed. -
#succ ⇒ Object
Returns the successor to str.
-
#succ! ⇒ Object
Equivalent to
String#succ, but modifies the receiver in place. -
#sum(n = 16) ⇒ Integer
Returns a basic n-bit checksum of the characters in str, where n is the optional
Fixnumparameter, defaulting to 16. -
#swapcase ⇒ String
Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
-
#swapcase! ⇒ String?
Equivalent to
String#swapcase, but modifies the receiver in place, returning str, ornilif no changes were made. -
#to_f ⇒ Float
Returns the result of interpreting leading characters in str as a floating point number.
-
#to_i(base = 10) ⇒ Integer
Returns the result of interpreting leading characters in str as an integer base base (between 2 and 36).
-
#to_s ⇒ Object
Returns the receiver.
-
#to_str ⇒ Object
Returns the receiver.
-
#to_sym ⇒ Object
Returns the
Symbolcorresponding to str, creating the symbol if it did not previously exist. -
#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.
-
#tr!(from_str, to_str) ⇒ String?
Translates str in place, using the same rules as
String#tr. -
#tr_s(from_str, to_str) ⇒ String
Processes a copy of str as described under
String#tr, then removes duplicate characters in regions that were affected by the translation. -
#tr_s!(from_str, to_str) ⇒ String?
Performs
String#tr_sprocessing on str in place, returning str, ornilif no changes were made. -
#unpack(format) ⇒ Array
Decodes str (which may contain binary data) according to the format string, returning an array of each value extracted.
-
#upcase ⇒ String
Returns a copy of str with all lowercase letters replaced with their uppercase counterparts.
-
#upcase! ⇒ String?
Upcases the contents of str, returning
nilif no changes were made. -
#upto(other_str, exclusive = false) {|s| ... } ⇒ String
Iterates through successive values, starting at str and ending at other_str inclusive, passing each value in turn to the block.
Methods included from Comparable
Methods included from Enumerable
#all?, #any?, #collect, #cycle, #detect, #drop, #drop_while, #each_cons, #each_slice, #each_with_index, #entries, #enum_cons, #enum_slice, #enum_with_index, #find, #find_all, #find_index, #first, #grep, #group_by, #inject, #map, #max, #max_by, #member?, #min, #min_by, #minmax, #minmax_by, #none?, #one?, #reduce, #reject, #reverse_each, #select, #sort, #sort_by, #take, #take_while, #to_a, #zip
Constructor Details
#new(str = "") ⇒ String
Returns a new string object containing a copy of str.
335 336 337 |
# File 'string.c', line 335 static VALUE rb_str_init(argc, argv, str) int argc; |
Instance Method Details
#%(arg) ⇒ String
Format---Uses str as a format specification, and returns the result
of applying it to arg. If the format specification contains more than
one substitution, then arg must be an Array containing
the values to be substituted. See Kernel::sprintf for details
of the format string.
"%05d" % 123 #=> "00123"
"%-5s: %08x" % [ "ID", self.id ] #=> "ID : 200e14d6"
461 462 463 |
# File 'string.c', line 461 static VALUE rb_str_format(str, arg) VALUE str, arg; |
#*(integer) ⇒ String
Copy---Returns a new String containing integer copies of
the receiver.
"Ho! " * 3 #=> "Ho! Ho! Ho! "
419 420 421 |
# File 'string.c', line 419 VALUE rb_str_times(str, times) VALUE str; |
#+(other_str) ⇒ String
Concatenation---Returns a new String containing
other_str concatenated to str.
"Hello from " + self.to_s #=> "Hello from main"
391 392 393 |
# File 'string.c', line 391 VALUE rb_str_plus(str1, str2) VALUE str1, str2; |
#<<(fixnum) ⇒ String #concat(fixnum) ⇒ String #<<(obj) ⇒ String #concat(obj) ⇒ String
Append---Concatenates the given object to str. If the object is a
Fixnum between 0 and 255, it is converted to a character before
concatenation.
a = "hello "
a << "world" #=> "hello world"
a.concat(33) #=> "hello world!"
853 854 855 |
# File 'string.c', line 853 VALUE rb_str_concat(str1, str2) VALUE str1, str2; |
#<=>(other_str) ⇒ -1, ...
Comparison---Returns -1 if other_str is less than, 0 if
other_str is equal to, and +1 if other_str is greater than
str. If the strings are of different lengths, and the strings are
equal when compared up to the shortest length, then the longer string is
considered greater than the shorter one. If the variable $= is
false, the comparison is based on comparing the binary values
of each character in the string. In older versions of Ruby, setting
$= allowed case-insensitive comparisons; this is now deprecated
in favor of using String#casecmp.
<=> is the basis for the methods <,
<=, >, >=, and between?,
included from module Comparable. The method
String#== does not use Comparable#==.
"abcdef" <=> "abcde" #=> 1
"abcdef" <=> "abcdef" #=> 0
"abcdef" <=> "abcdefg" #=> -1
"abcdef" <=> "ABCDEF" #=> 1
1016 1017 1018 |
# File 'string.c', line 1016 static VALUE rb_str_cmp_m(str1, str2) VALUE str1, str2; |
#==(obj) ⇒ Boolean
Equality---If obj is not a String, returns
false. Otherwise, returns true if str
<=> obj returns zero.
950 951 952 |
# File 'string.c', line 950 static VALUE rb_str_equal(str1, str2) VALUE str1, str2; |
#=~(obj) ⇒ Fixnum?
Match---If obj is a Regexp, use it as a pattern to match
against str,and returns the position the match starts, or
nil if there is no match. Otherwise, invokes
obj.=~, passing str as an argument. The default
=~ in Object returns false.
"cat o' 9 tails" =~ /\d/ #=> 7
"cat o' 9 tails" =~ 9 #=> false
1313 1314 1315 |
# File 'string.c', line 1313 static VALUE rb_str_match(x, y) VALUE x, y; |
#[](fixnum) ⇒ Fixnum? #[](fixnum, fixnum) ⇒ String? #[](range) ⇒ String? #[](regexp) ⇒ String? #[](regexp, fixnum) ⇒ String? #[](other_str) ⇒ String? #slice(fixnum) ⇒ Fixnum? #slice(fixnum, fixnum) ⇒ String? #slice(range) ⇒ String? #slice(regexp) ⇒ String? #slice(regexp, fixnum) ⇒ String? #slice(other_str) ⇒ String?
Element Reference---If passed a single Fixnum, returns the code
of the character at that position. If passed two Fixnum
objects, returns a substring starting at the offset given by the first, and
a length given by the second. If given a range, a substring containing
characters at offsets given by the range is returned. In all three cases, if
an offset is negative, it is counted from the end of str. Returns
nil if the initial offset falls outside the string, the length
is negative, or the beginning of the range is greater than the end.
If a Regexp is supplied, the matching portion of str is
returned. If a numeric parameter follows the regular expression, that
component of the MatchData is returned instead. If a
String is given, that string is returned if it occurs in
str. In both cases, nil is returned if there is no
match.
a = "hello there"
a[1] #=> 101
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
1638 1639 1640 |
# File 'string.c', line 1638 static VALUE rb_str_aref_m(argc, argv, str) int argc; |
#[]=(fixnum) ⇒ Object #[]=(fixnum) ⇒ Object #[]=(fixnum, fixnum) ⇒ Object #[]=(range) ⇒ Object #[]=(regexp) ⇒ Object #[]=(regexp, fixnum) ⇒ Object #[]=(other_str) ⇒ Object
Element Assignment---Replaces some or all of the content of str. The
portion of the string affected is determined using the same criteria as
String#[]. If the replacement string is not the same length as
the text it is replacing, the string will be adjusted accordingly. If the
regular expression or string is used as the index doesn't match a position
in the string, IndexError is raised. If the regular expression
form is used, the optional second Fixnum allows you to specify
which portion of the match to replace (effectively using the
MatchData indexing rules. The forms that take a
Fixnum will raise an IndexError if the value is
out of range; the Range form will raise a
RangeError, and the Regexp and String
forms will silently ignore the assignment.
1830 1831 1832 |
# File 'string.c', line 1830 static VALUE rb_str_aset_m(argc, argv, str) int argc; |
#each_byte {|fixnum| ... } ⇒ String
Passes each byte in str to the given block.
"hello".each_byte {|c| print c, ' ' }
produces:
104 101 108 108 111
3816 3817 3818 |
# File 'string.c', line 3816 static VALUE rb_str_each_byte(str) VALUE str; |
#length ⇒ Integer
Returns the length of str.
355 356 357 |
# File 'string.c', line 355 static VALUE rb_str_length(str) VALUE str; |
#capitalize ⇒ String
Returns a copy of str with the first character converted to uppercase and the remainder to lowercase.
"hello".capitalize #=> "Hello"
"HELLO".capitalize #=> "Hello"
"123ABC".capitalize #=> "123abc"
2952 2953 2954 |
# File 'string.c', line 2952 static VALUE rb_str_capitalize(str) VALUE str; |
#capitalize! ⇒ String?
Modifies str by converting the first character to uppercase and the
remainder to lowercase. Returns nil if no changes are made.
a = "hello"
a.capitalize! #=> "Hello"
a #=> "Hello"
a.capitalize! #=> nil
2912 2913 2914 |
# File 'string.c', line 2912 static VALUE rb_str_capitalize_bang(str) VALUE str; |
#casecmp(other_str) ⇒ -1, ...
Case-insensitive version of String#<=>.
"abcdef".casecmp("abcde") #=> 1
"aBcDeF".casecmp("abcdef") #=> 0
"abcdef".casecmp("abcdefg") #=> -1
"abcdef".casecmp("ABCDEF") #=> 0
1057 1058 1059 |
# File 'string.c', line 1057 static VALUE rb_str_casecmp(str1, str2) VALUE str1, str2; |
#center(integer, padstr) ⇒ String
If integer is greater than the length of str, returns a new
String of length integer with str centered and
padded with padstr; otherwise, returns str.
"hello".center(4) #=> "hello"
"hello".center(20) #=> " hello "
"hello".center(20, '123') #=> "1231231hello12312312"
4731 4732 4733 |
# File 'string.c', line 4731 static VALUE rb_str_center(argc, argv, str) int argc; |
#each_char {|cstr| ... } ⇒ String
Passes each character in str to the given block.
"hello".each_char {|c| print c, ' ' }
produces:
h e l l o
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 |
# File 'string.c', line 3856
static VALUE
rb_str_each_char(VALUE str)
{
int i, len, n;
const char *ptr;
RETURN_ENUMERATOR(str, 0, 0);
str = rb_str_new4(str);
ptr = RSTRING(str)->ptr;
len = RSTRING(str)->len;
for (i = 0; i < len; i += n) {
n = mbclen(ptr[i]);
rb_yield(rb_str_substr(str, i, n));
}
return str;
}
|
#chomp(separator = $/) ⇒ String
Returns a new String with the given record separator removed
from the end of str (if present). If $/ has not been
changed from the default Ruby record separator, then chomp also
removes carriage return characters (that is it will remove \n,
\r, and \r\n).
"hello".chomp #=> "hello"
"hello\n".chomp #=> "hello"
"hello\r\n".chomp #=> "hello"
"hello\n\r".chomp #=> "hello\n"
"hello\r".chomp #=> "hello"
"hello \n there".chomp #=> "hello \n there"
"hello".chomp("llo") #=> "he"
4086 4087 4088 |
# File 'string.c', line 4086 static VALUE rb_str_chomp(argc, argv, str) int argc; |
#chomp!(separator = $/) ⇒ String?
Modifies str in place as described for String#chomp,
returning str, or nil if no modifications were made.
3994 3995 3996 |
# File 'string.c', line 3994 static VALUE rb_str_chomp_bang(argc, argv, str) int argc; |
#chop ⇒ String
Returns a new String with the last character removed. If the
string ends with \r\n, both characters are removed. Applying
chop to an empty string returns an empty
string. String#chomp is often a safer alternative, as it leaves
the string unchanged if it doesn't end in a record separator.
"string\r\n".chop #=> "string"
"string\n\r".chop #=> "string\n"
"string\n".chop #=> "string"
"string".chop #=> "strin"
"x".chop.chop #=> ""
3920 3921 3922 |
# File 'string.c', line 3920 static VALUE rb_str_chop(str) VALUE str; |
#chop! ⇒ String?
Processes str as for String#chop, returning str,
or nil if str is the empty string. See also
String#chomp!.
3883 3884 3885 |
# File 'string.c', line 3883 static VALUE rb_str_chop_bang(str) VALUE str; |
#<<(fixnum) ⇒ String #concat(fixnum) ⇒ String #<<(obj) ⇒ String #concat(obj) ⇒ String
Append---Concatenates the given object to str. If the object is a
Fixnum between 0 and 255, it is converted to a character before
concatenation.
a = "hello "
a << "world" #=> "hello world"
a.concat(33) #=> "hello world!"
853 854 855 |
# File 'string.c', line 853 VALUE rb_str_concat(str1, str2) VALUE str1, str2; |
#count([other_str]) ⇒ Fixnum
Each other_str parameter defines a set of characters to count. The intersection of these sets defines the characters to count in str. Any other_str that starts with a caret (^) is negated. The sequence c1--c2 means all characters between c1 and c2.
a = "hello world"
a.count "lo" #=> 5
a.count "lo", "o" #=> 2
a.count "hello", "^l" #=> 4
a.count "ej-m" #=> 4
3451 3452 3453 |
# File 'string.c', line 3451 static VALUE rb_str_count(argc, argv, str) int argc; |
#crypt(other_str) ⇒ String
Applies a one-way cryptographic hash to str by invoking the standard
library function crypt. The argument is the salt string, which
should be two characters long, each character drawn from
[a-zA-Z0-9./].
4478 4479 4480 |
# File 'string.c', line 4478 static VALUE rb_str_crypt(str, salt) VALUE str, salt; |
#delete([other_str]) ⇒ String
Returns a copy of str with all characters in the intersection of its
arguments deleted. Uses the same rules for building the set of characters as
String#count.
"hello".delete "l","lo" #=> "heo"
"hello".delete "lo" #=> "he"
"hello".delete "aeiou", "^e" #=> "hell"
"hello".delete "ej-m" #=> "ho"
3300 3301 3302 |
# File 'string.c', line 3300 static VALUE rb_str_delete(argc, argv, str) int argc; |
#delete!([other_str]) ⇒ String?
Performs a delete operation in place, returning str, or
nil if str was not modified.
3244 3245 3246 |
# File 'string.c', line 3244 static VALUE rb_str_delete_bang(argc, argv, str) int argc; |
#downcase ⇒ String
Returns a copy of str with all uppercase letters replaced with their
lowercase counterparts. The operation is locale insensitive---only
characters A'' to Z'' are affected.
"hEllO".downcase #=> "hello"
2889 2890 2891 |
# File 'string.c', line 2889 static VALUE rb_str_downcase(str) VALUE str; |
#downcase! ⇒ String?
Downcases the contents of str, returning nil if no
changes were made.
2853 2854 2855 |
# File 'string.c', line 2853 static VALUE rb_str_downcase_bang(str) VALUE str; |
#dump ⇒ String
Produces a version of str with all nonprinting characters replaced by
\nnn notation and all special characters escaped.
2691 2692 2693 |
# File 'string.c', line 2691 VALUE rb_str_dump(str) VALUE str; |
#each(separator = $/) {|substr| ... } ⇒ String #each_line(separator = $/) {|substr| ... } ⇒ String
Splits str using the supplied parameter as the record separator
($/ by default), passing each substring in turn to the supplied
block. If a zero-length record separator is supplied, the string is split
into paragraphs delimited by multiple successive newlines.
print "Example one\n"
"hello\nworld".each {|s| p s}
print "Example two\n"
"hello\nworld".each('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each('') {|s| p s}
produces:
Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"
3734 3735 3736 |
# File 'string.c', line 3734 static VALUE rb_str_each_line(argc, argv, str) int argc; |
#each_byte {|fixnum| ... } ⇒ String
Passes each byte in str to the given block.
"hello".each_byte {|c| print c, ' ' }
produces:
104 101 108 108 111
3816 3817 3818 |
# File 'string.c', line 3816 static VALUE rb_str_each_byte(str) VALUE str; |
#each_char {|cstr| ... } ⇒ String
Passes each character in str to the given block.
"hello".each_char {|c| print c, ' ' }
produces:
h e l l o
3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 |
# File 'string.c', line 3856
static VALUE
rb_str_each_char(VALUE str)
{
int i, len, n;
const char *ptr;
RETURN_ENUMERATOR(str, 0, 0);
str = rb_str_new4(str);
ptr = RSTRING(str)->ptr;
len = RSTRING(str)->len;
for (i = 0; i < len; i += n) {
n = mbclen(ptr[i]);
rb_yield(rb_str_substr(str, i, n));
}
return str;
}
|
#each(separator = $/) {|substr| ... } ⇒ String #each_line(separator = $/) {|substr| ... } ⇒ String
Splits str using the supplied parameter as the record separator
($/ by default), passing each substring in turn to the supplied
block. If a zero-length record separator is supplied, the string is split
into paragraphs delimited by multiple successive newlines.
print "Example one\n"
"hello\nworld".each {|s| p s}
print "Example two\n"
"hello\nworld".each('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each('') {|s| p s}
produces:
Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"
3734 3735 3736 |
# File 'string.c', line 3734 static VALUE rb_str_each_line(argc, argv, str) int argc; |
#empty? ⇒ Boolean
Returns true if str has a length of zero.
"hello".empty? #=> false
"".empty? #=> true
372 373 374 |
# File 'string.c', line 372 static VALUE rb_str_empty(str) VALUE str; |
#end_with?([suffix]) ⇒ Boolean
Returns true if str ends with the suffix given.
4862 4863 4864 |
# File 'string.c', line 4862 static VALUE rb_str_end_with(argc, argv, str) int argc; |
#eql?(other) ⇒ Boolean
Two strings are equal if the have the same length and content.
977 978 979 |
# File 'string.c', line 977 static VALUE rb_str_eql(str1, str2) VALUE str1, str2; |
#gsub(pattern, replacement) ⇒ String #gsub(pattern) {|match| ... } ⇒ String
Returns a copy of str with all occurrences of pattern
replaced with either replacement or the value of the block. The
pattern will typically be a Regexp; if it is a
String then no regular expression metacharacters will be
interpreted (that is /\d/ will match a digit, but
'\d' will match a backslash followed by a 'd').
If a string is used as the replacement, special variables from the match
(such as $& and $1) cannot be substituted into it,
as substitution into the string occurs before the pattern match
starts. However, the sequences \1, \2, and so on
may be used to interpolate successive groups in the match.
In the block form, the current match string is passed in as a parameter, and
variables such as $1, $2, $`</code>,
$&, and $' will be set appropriately. The value
returned by the block will be substituted for the match on each call.
The result inherits any tainting in the original string or any supplied replacement string.
"hello".gsub(/[aeiou]/, '*') #=> "h*ll*"
"hello".gsub(/([aeiou])/, '<\1>') #=> "h<e>ll<o>"
"hello".gsub(/./) {|s| s[0].to_s + ' '} #=> "104 101 108 108 111 "
2277 2278 2279 |
# File 'string.c', line 2277 static VALUE rb_str_gsub(argc, argv, str) int argc; |
#gsub!(pattern, replacement) ⇒ String? #gsub!(pattern) {|match| ... } ⇒ String?
Performs the substitutions of String#gsub in place, returning
str, or nil if no substitutions were performed.
2236 2237 2238 |
# File 'string.c', line 2236 static VALUE rb_str_gsub_bang(argc, argv, str) int argc; |
#hash ⇒ Fixnum
Return a hash based on the string's length and content.
912 913 914 |
# File 'string.c', line 912 static VALUE rb_str_hash_m(str) VALUE str; |
#hex ⇒ Integer
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
4438 4439 4440 |
# File 'string.c', line 4438 static VALUE rb_str_hex(str) VALUE str; |
#include?(other_str) ⇒ Boolean #include?(fixnum) ⇒ Boolean
Returns true if str contains the given string or
character.
"hello".include? "lo" #=> true
"hello".include? "ol" #=> false
"hello".include? ?h #=> true
2500 2501 2502 |
# File 'string.c', line 2500 static VALUE rb_str_include(str, arg) VALUE str, arg; |
#index(substring[, offset]) ⇒ Fixnum? #index(fixnum[, offset]) ⇒ Fixnum? #index(regexp[, offset]) ⇒ Fixnum?
Returns the index of the first occurrence of the given substring,
character (fixnum), or pattern (regexp) in str. Returns
nil if not found. If the second parameter is present, it
specifies the position in the string to begin the search.
"hello".index('e') #=> 1
"hello".index('lo') #=> 3
"hello".index('a') #=> nil
"hello".index(101) #=> 1
"hello".index(/[aeiou]/, -3) #=> 4
1115 1116 1117 |
# File 'string.c', line 1115 static VALUE rb_str_index_m(argc, argv, str) int argc; |
#replace(other_str) ⇒ String
Replaces the contents and taintedness of str with the corresponding values in other_str.
s = "hello" #=> "hello"
s.replace "world" #=> "world"
2298 2299 2300 |
# File 'string.c', line 2298 static VALUE rb_str_replace(str, str2) VALUE str, str2; |
#insert(index, other_str) ⇒ String
Inserts other_str before the character at the given index, modifying str. Negative indices count from the end of the string, and insert after the given character. The intent is insert aString so that it starts at the given index.
"abcd".insert(0, 'X') #=> "Xabcd"
"abcd".insert(3, 'X') #=> "abcXd"
"abcd".insert(4, 'X') #=> "abcdX"
"abcd".insert(-3, 'X') #=> "abXcd"
"abcd".insert(-1, 'X') #=> "abcdX"
1868 1869 1870 |
# File 'string.c', line 1868 static VALUE rb_str_insert(str, idx, str2) VALUE str, idx, str2; |
#inspect ⇒ String
Returns a printable version of str, with special characters escaped.
str = "hello"
str[3] = 8
str.inspect #=> "hel\010o"
2615 2616 2617 |
# File 'string.c', line 2615 VALUE rb_str_inspect(str) VALUE str; |
#intern ⇒ Object #to_sym ⇒ Object
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"
4519 4520 4521 |
# File 'string.c', line 4519 VALUE rb_str_intern(s) VALUE s; |
#length ⇒ Integer
Returns the length of str.
355 356 357 |
# File 'string.c', line 355 static VALUE rb_str_length(str) VALUE str; |
#each(separator = $/) {|substr| ... } ⇒ String #each_line(separator = $/) {|substr| ... } ⇒ String
Splits str using the supplied parameter as the record separator
($/ by default), passing each substring in turn to the supplied
block. If a zero-length record separator is supplied, the string is split
into paragraphs delimited by multiple successive newlines.
print "Example one\n"
"hello\nworld".each {|s| p s}
print "Example two\n"
"hello\nworld".each('l') {|s| p s}
print "Example three\n"
"hello\n\n\nworld".each('') {|s| p s}
produces:
Example one
"hello\n"
"world"
Example two
"hel"
"l"
"o\nworl"
"d"
Example three
"hello\n\n\n"
"world"
3734 3735 3736 |
# File 'string.c', line 3734 static VALUE rb_str_each_line(argc, argv, str) int argc; |
#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"
4685 4686 4687 |
# File 'string.c', line 4685 static VALUE rb_str_ljust(argc, argv, str) int argc; |
#lstrip ⇒ String
Returns a copy of str with leading whitespace removed. See also
String#rstrip and String#strip.
" hello ".lstrip #=> "hello "
"hello".lstrip #=> "hello"
4198 4199 4200 |
# File 'string.c', line 4198 static VALUE rb_str_lstrip(str) VALUE str; |
#lstrip! ⇒ self?
Removes leading whitespace from str, returning nil if no
change was made. See also String#rstrip! and
String#strip!.
" hello ".lstrip #=> "hello "
"hello".lstrip! #=> nil
4164 4165 4166 |
# File 'string.c', line 4164 static VALUE rb_str_lstrip_bang(str) VALUE str; |
#match(pattern) ⇒ MatchData?
Converts pattern to a Regexp (if it isn't already one),
then invokes its match method on str.
'hello'.match('(.)\1') #=> #<MatchData:0x401b3d30>
'hello'.match('(.)\1')[0] #=> "ll"
'hello'.match(/(.)\1/)[0] #=> "ll"
'hello'.match('xx') #=> nil
1346 1347 1348 |
# File 'string.c', line 1346 static VALUE rb_str_match_m(str, re) VALUE str, re; |
#succ ⇒ String #next ⇒ String
Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.
If the increment generates a ``carry,'' the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.
"abcd".succ #=> "abce"
"THX1138".succ #=> "THX1139"
"<<koala>>".succ #=> "<<koalb>>"
"1999zzz".succ #=> "2000aaa"
"ZZZ9999".succ #=> "AAAA0000"
"***".succ #=> "**+"
1404 1405 1406 |
# File 'string.c', line 1404 static VALUE rb_str_succ(orig) VALUE orig; |
#succ! ⇒ String #next! ⇒ String
Equivalent to String#succ, but modifies the receiver in
place.
1456 1457 1458 |
# File 'string.c', line 1456 static VALUE rb_str_succ_bang(str) VALUE str; |
#oct ⇒ Integer
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
4460 4461 4462 |
# File 'string.c', line 4460 static VALUE rb_str_oct(str) VALUE str; |
#partition(sep) ⇒ Array
Searches the string for sep and returns the part before it, the sep, and the part after it. If sep is not found, returns str and two empty strings. If no argument is given, Enumerable#partition is called.
"hello".partition("l") #=> ["he", "l", "lo"]
"hello".partition("x") #=> ["hello", "", ""]
4753 4754 4755 |
# File 'string.c', line 4753 static VALUE rb_str_partition(argc, argv, str) int argc; |
#replace(other_str) ⇒ String
Replaces the contents and taintedness of str with the corresponding values in other_str.
s = "hello" #=> "hello"
s.replace "world" #=> "world"
2298 2299 2300 |
# File 'string.c', line 2298 static VALUE rb_str_replace(str, str2) VALUE str, str2; |
#reverse ⇒ String
Returns a new string with the characters from str in reverse order.
"stressed".reverse #=> "desserts"
2465 2466 2467 |
# File 'string.c', line 2465 static VALUE rb_str_reverse(str) VALUE str; |
#reverse! ⇒ String
Reverses str in place.
2435 2436 2437 |
# File 'string.c', line 2435 static VALUE rb_str_reverse_bang(str) VALUE str; |
#rindex(substring[, fixnum]) ⇒ Fixnum? #rindex(fixnum[, fixnum]) ⇒ Fixnum? #rindex(regexp[, fixnum]) ⇒ Fixnum?
Returns the index of the last occurrence of the given substring,
character (fixnum), or pattern (regexp) in str. Returns
nil if not found. If the second parameter is present, it
specifies the position in the string to end the search---characters beyond
this point will not be considered.
"hello".rindex('e') #=> 1
"hello".rindex('l') #=> 3
"hello".rindex('a') #=> nil
"hello".rindex(101) #=> 1
"hello".rindex(/[aeiou]/, -2) #=> 1
1228 1229 1230 |
# File 'string.c', line 1228 static VALUE rb_str_rindex_m(argc, argv, str) int argc; |
#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"
4708 4709 4710 |
# File 'string.c', line 4708 static VALUE rb_str_rjust(argc, argv, str) int argc; |
#rpartition(sep) ⇒ Array
Searches sep in the string from the end of the string, and returns the part before it, the sep, and the part after it. If sep is not found, returns two empty strings and str.
"hello".rpartition("l") #=> ["hel", "l", "o"]
"hello".rpartition("x") #=> ["", "", "hello"]
4800 4801 4802 |
# File 'string.c', line 4800 static VALUE rb_str_rpartition(str, sep) VALUE str; |
#rstrip ⇒ String
Returns a copy of str with trailing whitespace removed. See also
String#lstrip and String#strip.
" hello ".rstrip #=> " hello"
"hello".rstrip #=> "hello"
4257 4258 4259 |
# File 'string.c', line 4257 static VALUE rb_str_rstrip(str) VALUE str; |
#rstrip! ⇒ self?
Removes trailing whitespace from str, returning nil if
no change was made. See also String#lstrip! and
String#strip!.
" hello ".rstrip #=> " hello"
"hello".rstrip! #=> nil
4220 4221 4222 |
# File 'string.c', line 4220 static VALUE rb_str_rstrip_bang(str) VALUE str; |
#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
4375 4376 4377 |
# File 'string.c', line 4375 static VALUE rb_str_scan(str, pat) VALUE str, pat; |
#length ⇒ Integer
Returns the length of str.
355 356 357 |
# File 'string.c', line 355 static VALUE rb_str_length(str) VALUE str; |
#[](fixnum) ⇒ Fixnum? #[](fixnum, fixnum) ⇒ String? #[](range) ⇒ String? #[](regexp) ⇒ String? #[](regexp, fixnum) ⇒ String? #[](other_str) ⇒ String? #slice(fixnum) ⇒ Fixnum? #slice(fixnum, fixnum) ⇒ String? #slice(range) ⇒ String? #slice(regexp) ⇒ String? #slice(regexp, fixnum) ⇒ String? #slice(other_str) ⇒ String?
Element Reference---If passed a single Fixnum, returns the code
of the character at that position. If passed two Fixnum
objects, returns a substring starting at the offset given by the first, and
a length given by the second. If given a range, a substring containing
characters at offsets given by the range is returned. In all three cases, if
an offset is negative, it is counted from the end of str. Returns
nil if the initial offset falls outside the string, the length
is negative, or the beginning of the range is greater than the end.
If a Regexp is supplied, the matching portion of str is
returned. If a numeric parameter follows the regular expression, that
component of the MatchData is returned instead. If a
String is given, that string is returned if it occurs in
str. In both cases, nil is returned if there is no
match.
a = "hello there"
a[1] #=> 101
a[1,3] #=> "ell"
a[1..3] #=> "ell"
a[-3,2] #=> "er"
a[-4..-2] #=> "her"
a[12..-1] #=> nil
a[-2..-4] #=> ""
a[/[aeiou](.)\1/] #=> "ell"
a[/[aeiou](.)\1/, 0] #=> "ell"
a[/[aeiou](.)\1/, 1] #=> "l"
a[/[aeiou](.)\1/, 2] #=> nil
a["lo"] #=> "lo"
a["bye"] #=> nil
1638 1639 1640 |
# File 'string.c', line 1638 static VALUE rb_str_aref_m(argc, argv, str) int argc; |
#slice!(fixnum) ⇒ Fixnum? #slice!(fixnum, fixnum) ⇒ String? #slice!(range) ⇒ String? #slice!(regexp) ⇒ String? #slice!(other_str) ⇒ String?
Deletes the specified portion from str, and returns the portion
deleted. The forms that take a Fixnum will raise an
IndexError if the value is out of range; the Range
form will raise a RangeError, and the Regexp and
String forms will silently ignore the assignment.
string = "this is a string"
string.slice!(2) #=> 105
string.slice!(3..6) #=> " is "
string.slice!(/s.*t/) #=> "sa st"
string.slice!("r") #=> "r"
string #=> "thing"
1906 1907 1908 |
# File 'string.c', line 1906 static VALUE rb_str_slice_bang(argc, argv, str) int argc; |
#split(pattern = $;, [limit]) ⇒ Array
Divides str into substrings based on a delimiter, returning an array of these substrings.
If pattern is a String, then its contents are used as
the delimiter when splitting str. If pattern is a single
space, str is split on whitespace, with leading whitespace and runs
of contiguous whitespace characters ignored.
If pattern is a Regexp, str is divided where the
pattern matches. Whenever the pattern matches a zero-length string,
str is split into individual characters.
If pattern is omitted, the value of $; is used. If
$; is nil (which is the default), str is
split on whitespace as if ` ' were specified.
If the limit parameter is omitted, trailing null fields are
suppressed. If limit is a positive number, at most that number of
fields will be returned (if limit is 1, the entire
string is returned as the only entry in an array). If negative, there is no
limit to the number of fields returned, and trailing null fields are not
suppressed.
" now's the time".split #=> ["now's", "the", "time"]
" now's the time".split(' ') #=> ["now's", "the", "time"]
" now's the time".split(/ /) #=> ["", "now's", "", "the", "time"]
"1, 2.34,56, 7".split(%r{,\s*}) #=> ["1", "2.34", "56", "7"]
"hello".split(//) #=> ["h", "e", "l", "l", "o"]
"hello".split(//, 3) #=> ["h", "e", "llo"]
"hi mom".split(%r{\s*}) #=> ["h", "i", "m", "o", "m"]
"mellow yellow".split("ello") #=> ["m", "w y", "w"]
"1,2,,3,4,,".split(',') #=> ["1", "2", "", "3", "4"]
"1,2,,3,4,,".split(',', 4) #=> ["1", "2", "", "3,4,,"]
"1,2,,3,4,,".split(',', -4) #=> ["1", "2", "", "3", "4", "", ""]
3527 3528 3529 |
# File 'string.c', line 3527 static VALUE rb_str_split_m(argc, argv, str) int argc; |
#squeeze([other_str]) ⇒ String
Builds a set of characters from the other_str parameter(s) using the
procedure described for String#count. Returns a new string
where runs of the same character that occur in this set are replaced by a
single character. If no arguments are given, all runs of identical
characters are replaced by a single character.
"yellow moon".squeeze #=> "yelow mon"
" now is the".squeeze(" ") #=> " now is the"
"putters shoot balls".squeeze("m-z") #=> "puters shot balls"
3384 3385 3386 |
# File 'string.c', line 3384 static VALUE rb_str_squeeze(argc, argv, str) int argc; |
#squeeze!([other_str]) ⇒ String?
Squeezes str in place, returning either str, or
nil if no changes were made.
3320 3321 3322 |
# File 'string.c', line 3320 static VALUE rb_str_squeeze_bang(argc, argv, str) int argc; |
#start_with?([prefix]) ⇒ Boolean
Returns true if str starts with the prefix given.
4835 4836 4837 |
# File 'string.c', line 4835 static VALUE rb_str_start_with(argc, argv, str) int argc; |
#strip ⇒ String
Returns a copy of str with leading and trailing whitespace removed.
" hello ".strip #=> "hello"
"\tgoodbye\r\n".strip #=> "goodbye"
4297 4298 4299 |
# File 'string.c', line 4297 static VALUE rb_str_strip(str) VALUE str; |
#strip! ⇒ String?
Removes leading and trailing whitespace from str. Returns
nil if str was not altered.
4275 4276 4277 |
# File 'string.c', line 4275 static VALUE rb_str_strip_bang(str) VALUE str; |
#sub(pattern, replacement) ⇒ String #sub(pattern) {|match| ... } ⇒ String
Returns a copy of str with the first occurrence of
pattern replaced with either replacement or the value of the
block. The pattern will typically be a Regexp; if it is
a String then no regular expression metacharacters will be
interpreted (that is /\d/ will match a digit, but
'\d' will match a backslash followed by a 'd').
If the method call specifies replacement, special variables such as
$& will not be useful, as substitution into the string occurs
before the pattern match starts. However, the sequences \1,
\2, etc., may be used.
In the block form, the current match string is passed in as a parameter, and
variables such as $1, $2, $`</code>,
$&, and $' will be set appropriately. The value
returned by the block will be substituted for the match on each call.
The result inherits any tainting in the original string or any supplied replacement string.
"hello".sub(/[aeiou]/, '*') #=> "h*llo"
"hello".sub(/([aeiou])/, '<\1>') #=> "h<e>llo"
"hello".sub(/./) {|s| s[0].to_s + ' ' } #=> "104 ello"
2088 2089 2090 |
# File 'string.c', line 2088 static VALUE rb_str_sub(argc, argv, str) int argc; |
#sub!(pattern, replacement) ⇒ String? #sub!(pattern) {|match| ... } ⇒ String?
Performs the substitutions of String#sub in place,
returning str, or nil if no substitutions were
performed.
1994 1995 1996 |
# File 'string.c', line 1994 static VALUE rb_str_sub_bang(argc, argv, str) int argc; |
#succ ⇒ String #next ⇒ String
Returns the successor to str. The successor is calculated by incrementing characters starting from the rightmost alphanumeric (or the rightmost character if there are no alphanumerics) in the string. Incrementing a digit always results in another digit, and incrementing a letter results in another letter of the same case. Incrementing nonalphanumerics uses the underlying character set's collating sequence.
If the increment generates a ``carry,'' the character to the left of it is incremented. This process repeats until there is no carry, adding an additional character if necessary.
"abcd".succ #=> "abce"
"THX1138".succ #=> "THX1139"
"<<koala>>".succ #=> "<<koalb>>"
"1999zzz".succ #=> "2000aaa"
"ZZZ9999".succ #=> "AAAA0000"
"***".succ #=> "**+"
1404 1405 1406 |
# File 'string.c', line 1404 static VALUE rb_str_succ(orig) VALUE orig; |
#succ! ⇒ String #next! ⇒ String
Equivalent to String#succ, but modifies the receiver in
place.
1456 1457 1458 |
# File 'string.c', line 1456 static VALUE rb_str_succ_bang(str) VALUE str; |
#sum(n = 16) ⇒ Integer
Returns a basic n-bit checksum of the characters in str,
where n is the optional Fixnum parameter, defaulting
to 16. The result is simply the sum of the binary value of each character in
str modulo 2n - 1. This is not a particularly good
checksum.
4550 4551 4552 |
# File 'string.c', line 4550 static VALUE rb_str_sum(argc, argv, str) int argc; |
#swapcase ⇒ String
Returns a copy of str with uppercase alphabetic characters converted to lowercase and lowercase characters converted to uppercase.
"Hello".swapcase #=> "hELLO"
"cYbEr_PuNk11".swapcase #=> "CyBeR_pUnK11"
3010 3011 3012 |
# File 'string.c', line 3010 static VALUE rb_str_swapcase(str) VALUE str; |
#swapcase! ⇒ String?
Equivalent to String#swapcase, but modifies the receiver in
place, returning str, or nil if no changes were made.
2970 2971 2972 |
# File 'string.c', line 2970 static VALUE rb_str_swapcase_bang(str) VALUE str; |
#to_f ⇒ Float
Returns the result of interpreting leading characters in str as a
floating point number. Extraneous characters past the end of a valid number
are ignored. If there is not a valid number at the start of str,
0.0 is returned. This method never raises an exception.
"123.45e1".to_f #=> 1234.5
"45.67 degrees".to_f #=> 45.67
"thx1138".to_f #=> 0.0
2575 2576 2577 |
# File 'string.c', line 2575 static VALUE rb_str_to_f(str) VALUE str; |
#to_i(base = 10) ⇒ Integer
Returns the result of interpreting leading characters in str as an
integer base base (between 2 and 36). Extraneous characters past the
end of a valid number are ignored. If there is not a valid number at the
start of str, 0 is returned. This method never raises an
exception.
"12345".to_i #=> 12345
"99 red balloons".to_i #=> 99
"0a".to_i #=> 0
"0a".to_i(16) #=> 10
"hello".to_i #=> 0
"1100101".to_i(2) #=> 101
"1100101".to_i(8) #=> 294977
"1100101".to_i(10) #=> 1100101
"1100101".to_i(16) #=> 17826049
2541 2542 2543 |
# File 'string.c', line 2541 static VALUE rb_str_to_i(argc, argv, str) int argc; |
#to_s ⇒ String #to_str ⇒ String
Returns the receiver.
2591 2592 2593 |
# File 'string.c', line 2591 static VALUE rb_str_to_s(str) VALUE str; |
#to_s ⇒ String #to_str ⇒ String
Returns the receiver.
2591 2592 2593 |
# File 'string.c', line 2591 static VALUE rb_str_to_s(str) VALUE str; |
#intern ⇒ Object #to_sym ⇒ Object
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"
4519 4520 4521 |
# File 'string.c', line 4519 VALUE rb_str_intern(s) VALUE s; |
#tr(from_str, to_str) ⇒ String
Returns a copy of str with the characters in from_str replaced
by the corresponding characters in to_str. If to_str is
shorter than from_str, it is padded with its last character. Both
strings may use the c1--c2 notation to denote ranges of characters, and
from_str may start with a ^, which denotes all
characters except those listed.
"hello".tr('aeiou', '*') #=> "h*ll*"
"hello".tr('^aeiou', '*') #=> "*e**o"
"hello".tr('el', 'ip') #=> "hippo"
"hello".tr('a-y', 'b-z') #=> "ifmmp"
3192 3193 3194 |
# File 'string.c', line 3192 static VALUE rb_str_tr(str, src, repl) VALUE str, src, repl; |
#tr!(from_str, to_str) ⇒ String?
Translates str in place, using the same rules as
String#tr. Returns str, or nil if no
changes were made.
3167 3168 3169 |
# File 'string.c', line 3167 static VALUE rb_str_tr_bang(str, src, repl) VALUE str, src, repl; |
#tr_s(from_str, to_str) ⇒ String
Processes a copy of str as described under String#tr,
then removes duplicate characters in regions that were affected by the
translation.
"hello".tr_s('l', 'r') #=> "hero"
"hello".tr_s('el', '*') #=> "h*o"
"hello".tr_s('el', 'hx') #=> "hhxo"
3425 3426 3427 |
# File 'string.c', line 3425 static VALUE rb_str_tr_s(str, src, repl) VALUE str, src, repl; |
#tr_s!(from_str, to_str) ⇒ String?
Performs String#tr_s processing on str in place,
returning str, or nil if no changes were made.
3404 3405 3406 |
# File 'string.c', line 3404 static VALUE rb_str_tr_s_bang(str, src, repl) VALUE str, src, repl; |
#unpack(format) ⇒ Array
Decodes str (which may contain binary data) according to the
format string, returning an array of each value extracted. The
format string consists of a sequence of single-character directives,
summarized in the table at the end of this entry.
Each directive may be followed
by a number, indicating the number of times to repeat with this
directive. An asterisk (<code>*</code>'') will use up all remaining elements. The directives <code>sSiIlL</code> may each be followed by an underscore (<code>_'') to use the underlying
platform's native size for the specified type; otherwise, it uses a
platform-independent consistent size. Spaces are ignored in the
format string. See also Array#pack.
"abc \0\0abc \0\0".unpack('A6Z6') #=> ["abc", "abc "]
"abc \0\0".unpack('a3a3') #=> ["abc", " \000\000"]
"abc \0abc \0".unpack('Z*Z*') #=> ["abc ", "abc "]
"aa".unpack('b8B8') #=> ["10000110", "01100001"]
"aaa".unpack('h2H2c') #=> ["16", "61", 97]
"\xfe\xff\xfe\xff".unpack('sS') #=> [-2, 65534]
"now=20is".unpack('M*') #=> ["now is"]
"whole".unpack('xax2aX2aX1aX2a') #=> ["h", "e", "l", "l", "o"]
This table summarizes the various formats and the Ruby classes returned by each.
Format | Returns | Function
-------+---------+-----------------------------------------
A | String | with trailing nulls and spaces removed
-------+---------+-----------------------------------------
a | String | string
-------+---------+-----------------------------------------
B | String | extract bits from each character (msb first)
-------+---------+-----------------------------------------
b | String | extract bits from each character (lsb first)
-------+---------+-----------------------------------------
C | Fixnum | extract a character as an unsigned integer
-------+---------+-----------------------------------------
c | Fixnum | extract a character as an integer
-------+---------+-----------------------------------------
d,D | Float | treat sizeof(double) characters as
| | a native double
-------+---------+-----------------------------------------
E | Float | treat sizeof(double) characters as
| | a double in little-endian byte order
-------+---------+-----------------------------------------
e | Float | treat sizeof(float) characters as
| | a float in little-endian byte order
-------+---------+-----------------------------------------
f,F | Float | treat sizeof(float) characters as
| | a native float
-------+---------+-----------------------------------------
G | Float | treat sizeof(double) characters as
| | a double in network byte order
-------+---------+-----------------------------------------
g | Float | treat sizeof(float) characters as a
| | float in network byte order
-------+---------+-----------------------------------------
H | String | extract hex nibbles from each character
| | (most significant first)
-------+---------+-----------------------------------------
h | String | extract hex nibbles from each character
| | (least significant first)
-------+---------+-----------------------------------------
I | Integer | treat sizeof(int) (modified by _)
| | successive characters as an unsigned
| | native integer
-------+---------+-----------------------------------------
i | Integer | treat sizeof(int) (modified by _)
| | successive characters as a signed
| | native integer
-------+---------+-----------------------------------------
L | Integer | treat four (modified by _) successive
| | characters as an unsigned native
| | long integer
-------+---------+-----------------------------------------
l | Integer | treat four (modified by _) successive
| | characters as a signed native
| | long integer
-------+---------+-----------------------------------------
M | String | quoted-printable
-------+---------+-----------------------------------------
m | String | base64-encoded
-------+---------+-----------------------------------------
N | Integer | treat four characters as an unsigned
| | long in network byte order
-------+---------+-----------------------------------------
n | Fixnum | treat two characters as an unsigned
| | short in network byte order
-------+---------+-----------------------------------------
P | String | treat sizeof(char *) characters as a
| | pointer, and return \emph{len} characters
| | from the referenced location
-------+---------+-----------------------------------------
p | String | treat sizeof(char *) characters as a
| | pointer to a null-terminated string
-------+---------+-----------------------------------------
Q | Integer | treat 8 characters as an unsigned
| | quad word (64 bits)
-------+---------+-----------------------------------------
q | Integer | treat 8 characters as a signed
| | quad word (64 bits)
-------+---------+-----------------------------------------
S | Fixnum | treat two (different if _ used)
| | successive characters as an unsigned
| | short in native byte order
-------+---------+-----------------------------------------
s | Fixnum | Treat two (different if _ used)
| | successive characters as a signed short
| | in native byte order
-------+---------+-----------------------------------------
U | Integer | UTF-8 characters as unsigned integers
-------+---------+-----------------------------------------
u | String | UU-encoded
-------+---------+-----------------------------------------
V | Fixnum | treat four characters as an unsigned
| | long in little-endian byte order
-------+---------+-----------------------------------------
v | Fixnum | treat two characters as an unsigned
| | short in little-endian byte order
-------+---------+-----------------------------------------
w | Integer | BER-compressed integer (see Array.pack)
-------+---------+-----------------------------------------
X | --- | skip backward one character
-------+---------+-----------------------------------------
x | --- | skip forward one character
-------+---------+-----------------------------------------
Z | String | with trailing nulls removed
| | upto first null with *
-------+---------+-----------------------------------------
@ | --- | skip to the offset given by the
| | length argument
-------+---------+-----------------------------------------
1303 1304 1305 |
# File 'pack.c', line 1303 static VALUE pack_unpack(str, fmt) VALUE str, fmt; |
#upcase ⇒ String
Returns a copy of str with all lowercase letters replaced with their
uppercase counterparts. The operation is locale insensitive---only
characters a'' to z'' are affected.
"hEllO".upcase #=> "HELLO"
2835 2836 2837 |
# File 'string.c', line 2835 static VALUE rb_str_upcase(str) VALUE str; |
#upcase! ⇒ String?
Upcases the contents of str, returning nil if no changes
were made.
2799 2800 2801 |
# File 'string.c', line 2799 static VALUE rb_str_upcase_bang(str) VALUE str; |
#upto(other_str, exclusive = false) {|s| ... } ⇒ String
Iterates through successive values, starting at str and
ending at other_str inclusive, passing each value in turn to
the block. The String#succ method is used to generate
each value. If optional second argument exclusive is omitted or is false,
the last value will be included; otherwise it will be excluded.
"a8".upto("b6") {|s| print s, ' ' }
for s in "a8".."b6"
print s, ' '
end
produces:
a8 a9 b0 b1 b2 b3 b4 b5 b6
a8 a9 b0 b1 b2 b3 b4 b5 b6
1515 1516 1517 |
# File 'string.c', line 1515 static VALUE rb_str_upto_m(argc, argv, beg) int argc; |