Programming Ruby
The Pragmatic Programmer's Guide
class String
Parent:
Object
Version:
1.6
Index:
new
%
*
+
<<
<=>
==
===
=~
[ ]
[ ]=
~
capitalize
capitalize!
center
chomp
chomp!
chop
chop!
concat
count
crypt
delete
delete!
downcase
downcase!
dump
each
each_byte
each_line
empty?
gsub
gsub!
hash
hex
include?
index
intern
length
ljust
next
next!
oct
replace
reverse
reverse!
rindex
rjust
scan
size
slice
slice!
split
squeeze
squeeze!
strip
strip!
sub
sub!
succ
succ!
sum
swapcase
swapcase!
to_f
to_i
to_s
to_str
tr
tr!
tr_s
tr_s!
unpack
upcase
upcase!
upto
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 (see page
202).
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#[]=
.
mixins
Comparable:
<, <=, ==, >=, >, between?
Enumerable:
collect, detect, each_with_index, entries, find, find_all, grep,
include?, map, max, member?, min, reject, select, sort, to_a
class methods
new
String.new(
aString )
->
aNewString
Returns a new string object containing a copy of
aString.
instance methods
Format---Uses
str as a format
specification, and returns the result of applying it to
arg. If the format specification contains more than one
substitution, then
arg must be an
Array containing the
values to be substituted. See
Kernel::sprintf
on page 423 for details of the format string.
"%05d" % 123
サ
"00123"
"%-5s: %08x" % [ "ID", self.id ]
サ
"ID[visible space][visible space][visible space]:[visible space]200e1670"
*
str *
anInteger
->
aString
Copy---Returns a new
String containing
anInteger copies of
the receiver.
"Ho! " * 3
サ
"Ho! Ho! Ho! "
+
str +
aString
->
aNewString
Concatenation---Returns a new
String containing
aString concatenated to
str.
"Hello from " + self.to_s
サ
"Hello from main"
<<
str <<
aFixnum ->
str
str <<
anObject ->
str
Append---Concatenates the given object to
str. If the object is a
Fixnum between 0 and 255, it is converted to a character
before concatenation.
a = "hello "
a << "world"
サ
"hello world"
a << 33
サ
"hello world!"
a
サ
"hello world!"
<=>
str <=>
aString
-> -1, 0, +1
Comparison---Returns -1 if
str is less than, 0
if
str is equal to, and +1 if
str is greater than
aString. 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.
If
$= is not
false, then the comparison is
case insensitive.
[The locale is ignored when
case-insensitive comparisons are performed, so ``\"o'' will not
match ``\"O''.]
<=> 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
$= = true
"abcdef" <=> "ABCDEF"
サ
0
==
str ==
anObject
->
true or
false
Equality---If
anObject is not a
String, returns
false. Otherwise, returns
true if
str <=>
anObject returns zero.
===
str ===
anObject
->
true or
false
Case Equality---Synonym for
String#==
.
=~
str =~
anObject
->
aFixnum or
nil
Match---If
anObject is a
Regexp or a
String, uses it as a
pattern to match against
str. Returns
the position the match starts, or
nil if there is no match.
Otherwise, invokes
anObject.=~, passing
str as an argument. The
default
=~ in
Object returns
false.
"cat o' 9 tails" =~ "\\d"
サ
7
"cat o' 9 tails" =~ /\d/
サ
7
"cat o' 9 tails" =~ 9
サ
false
[ ]
str[
aFixnum ] ->
aFixnum or
nil
str[
aFixnum,
aFixnum ] ->
aString or
nil
str[
aRange ] ->
aString or
nil
str[
aRegexp ] ->
aString or
nil
str[
aString ] ->
aString or
nil
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
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[-2..-4]
サ
nil
a[/th[aeiou]/]
サ
"the"
a["lo"]
サ
"lo"
a["bye"]
サ
nil
[ ]=
str[
aFixnum ] =
aFixnum
str[
aFixnum ] =
aString
str[
aFixnum,
aFixnum ] =
aString
str[
aRange ] =
aString
str[
aRegexp ] =
aString
str[
aString ] =
aString
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.
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.
a = "hello"; a[2] = 96; a
サ
"he`lo"
a = "hello"; a[2, 4] = "xyz"; a
サ
"hexyz"
a = "hello"; a[-4, 2] = "xyz"; a
サ
"hxyzlo"
a = "hello"; a[2..4] = "xyz"; a
サ
"hexyz"
a = "hello"; a[-4..-2] = "xyz"; a
サ
"hxyzo"
a = "hello"; a[/[el]+/] = "xyz"; a
サ
"hxyzo"
a = "hello"; a["l"] = "xyz"; a
サ
"hexyzlo"
a = "hello"; a["ll"] = "xyz"; a
サ
"hexyzo"
a = "hello"; a["bad"] = "xyz"; a
サ
"hello"
a = "hello"; a[2, 0] = "xyz"; a
サ
"hexyzllo"
Equivalent to
$_
=~ str
.
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"
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
center
str.center(
anInteger )
->
aString
If
anInteger is greater than the length of
str, returns a
new
String of length
anInteger with
str centered
between spaces; otherwise,
returns
str.
"hello".center(4)
サ
"hello"
"hello".center(20)
サ
"[visible space][visible space][visible space][visible space][visible space][visible space][visible space]hello[visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space]"
chomp
str.chomp(
aString=
$/ )
->
aString
Returns a new
String with the given record separator removed
from the end of
str (if present).
"hello".chomp
サ
"hello"
"hello\n".chomp
サ
"hello"
"hello \n there".chomp
サ
"hello \n there"
"hello".chomp("llo")
サ
"he"
chomp!
str.chomp!(
aString=
$/ )
->
str or
nil
Modifies
str in place as described for
String#chomp
,
returning
str, or
nil if no modifications were made.
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
サ
""
chop!
str.chop!
->
str or
nil
Processes
str as for
String#chop
, returning
str,
or
nil if
str is the empty string. See also
String#chomp!
.
concat
str.concat(
aFixnum ) ->
str
str.concat(
anObject ) ->
str
Synonym for
String#<<
.
count
str.count(
[
aString
]+
)
->
aFixnum
Each
aString parameter defines a set of characters to
count. The intersection of these sets defines the characters to count
in
str. Any
aString that starts with a caret (^) is
negated. The sequence c
1--c
2 means all characters between
c
1 and c
2.
a = "hello world"
a.count "lo"
サ
5
a.count "lo", "o"
サ
2
a.count "hello", "^l"
サ
4
a.count "ej-m"
サ
4
crypt
str.crypt(
aString )
->
aString
Applies a one-way
cryptographic hash to
str by invoking the standard library
function
crypt. The argument is the salt
string, which should be two characters long, each character
drawn from
[a-zA-Z0-9./].
delete
str.delete(
[
aString
]+
)
->
aString
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"
delete!
str.delete!(
[
aString
]+
)
->
str or
nil
Performs a
delete operation in place, returning
str, or
nil if
str was not modified.
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"
Downcases the contents of
str, returning
nil if no
changes were made.
Produces a version of
str with all nonprinting characters
replaced by
\nnn notation and all special characters
escaped.
each
str.each(
aString=
$/ )
{| substr | block }
->
str
Splits
str using the supplied parameter as the record
separator (
$/ by default), passing each substring in turn
to the supplied block. If a zero-length record separator is
supplied, the string is split on
\n characters, except
that multiple successive newlines are appended together.
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"
each_byte
str.each_byte {| aFixnum | block }
->
str
Passes each byte in
str to the given block.
"hello".each_byte {|c| print c, ' ' }
produces:
each_line
str.each_line(
aString=
$/ )
{| substr | block }
->
str
Synonym for
String#each
.
empty?
str.empty? ->
true or
false
Returns
true if
str has a length of zero.
"hello".empty?
サ
false
"".empty?
サ
true
gsub
str.gsub(
pattern,
replacement )
->
aString
str.gsub(
pattern ) {| match | block }
->
aString
Returns a copy of
str with
all occurrences of
pattern replaced with either
replacement or the
value of the block. 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. These sequences are shown in
Table 22.7 on page 371.
Backslash sequences in substitution
strings
Sequence
Text That Is Substituted
1,円 2,円 ... 9円
The value matched by the
nth grouped subexpression
\&
The last match
\`
The part of the string before the match
\'
The part of the string after the match
\+
The highest-numbered group matched
In the block form, the current match is passed in as a
parameter, and variables such as
1ドル,
2ドル,
$`,
$&, 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 "
gsub!
str.gsub!(
pattern,
replacement )
->
str or
nil
str.gsub!(
pattern ) {| match | block }
->
str or
nil
Performs the substitutions of
String#gsub
in place,
returning
str, or
nil if no substitutions were
performed.
Generates a
Fixnum hash value for
str. If
$= is
true, the hash will be case insensitive.
$= = true
hash = { 'cat' => 'Feline', 'dog' => 'canine' }
hash['cat']
サ
"Feline"
hash['cAt']
サ
"Feline"
$= = false
hash.rehash # re-calculate hash values
サ
{"cat"=>"Feline", "dog"=>"canine"}
hash['cat']
サ
"Feline"
hash['cAt']
サ
nil
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
include?
str.include?
aString ->
true or
false
str.include?
aFixnum ->
true or
false
Returns
true if
str contains the given string or character.
"hello".include? "lo"
サ
true
"hello".include? "ol"
サ
false
"hello".include? ?h
サ
true
index
str.index(
aString [,
anOffset
] )
->
aFixnum or
nil
str.index(
aFixnum [,
anOffset
] )
->
aFixnum or
nil
str.index(
aRegexp [,
anOffset
] )
->
aFixnum or
nil
Returns the index of the first occurrence of the given substring,
character, or pattern 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
Returns the
Symbol corresponding to
str, creating the
symbol if it did not previously exist. See
Symbol#id2name
on page 384.
"Koala".intern
サ
:Koala
length
str.length ->
anInteger
Returns the length of
str.
ljust
str.ljust(
anInteger )
->
aString
If
anInteger is greater than the length of
str, returns a
new
String of length
anInteger with
str left
justified and space padded; otherwise, returns
str.
"hello".ljust(4)
サ
"hello"
"hello".ljust(20)
サ
"hello[visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space]"
Synonym for
String#succ
.
Synonym for
String#succ!
.
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
replace
str.replace(
aString )
->
str
Replaces the contents and taintedness of
str with the
corresponding values in
aString.
s = "hello"
サ
"hello"
s.replace "world"
サ
"world"
Returns a new string with the characters from
str in
reverse order.
"stressed".reverse
サ
"desserts"
Reverses
str in place.
rindex
str.rindex(
aString [,
aFixnum
] )
->
aFixnum or
nil
str.rindex(
aFixnum [,
aFixnum
] )
->
aFixnum or
nil
str.rindex(
aRegexp [,
aFixnum
] )
->
aFixnum or
nil
Returns the index of the last occurrence of the given substring,
character, or pattern 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
rjust
str.rjust(
anInteger )
->
aString
If
anInteger is greater than the length of
str,
returns a new
String of length
anInteger with
str right justified and space padded;
otherwise, returns
str.
"hello".rjust(4)
サ
"hello"
"hello".rjust(20)
サ
"[visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space][visible space]hello"
scan
str.scan(
pattern ) ->
anArray
str.scan(
pattern ) {| match, ...| block }
->
str
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(/(.)(.)/) {|a,b| print b, a }
print "\n"
produces:
<<cruel>> <<world>>
rceu lowlr
size
str.size ->
anInteger
Synonym for
String#length
.
slice
str.slice(
aFixnum ) ->
aFixnum or
nil
str.slice(
aFixnum,
aFixnum )
->
aString or
nil
str.slice(
aRange ) ->
aString or
nil
str.slice(
aRegexp ) ->
aString or
nil
str.slice(
aString ) ->
aString or
nil
Synonym for
String#[ ]
.
a = "hello there"
a.slice(1)
サ
101
a.slice(1,3)
サ
"ell"
a.slice(1..3)
サ
"ell"
a.slice(-3,2)
サ
"er"
a.slice(-4..-2)
サ
"her"
a.slice(-2..-4)
サ
nil
a.slice(/th[aeiou]/)
サ
"the"
a.slice("lo")
サ
"lo"
a.slice("bye")
サ
nil
slice!
str.slice!(
aFixnum ) ->
aFixnum or
nil
str.slice!(
aFixnum,
aFixnum )
->
aString or
nil
str.slice!(
aRange ) ->
aString or
nil
str.slice!(
aRegexp ) ->
aString or
nil
str.slice!(
aString ) ->
aString or
nil
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"
split
str.split(
pattern=
$;,
[
limit
] ) ->
anArray
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 `[visible space]' were specified.
If the
limit parameter is omitted, trailing null fields are
supressed. 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 supressed.
" 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(/,\s*/)
サ
["1", "2.34", "56", "7"]
"hello".split(//)
サ
["h", "e", "l", "l", "o"]
"hello".split(//, 3)
サ
["h", "e", "llo"]
"hi mom".split(/\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", "", ""]
squeeze
str.squeeze(
[
aString
]*
)
->
aNewString
Builds a set of characters from the
aString parameter(s)
using the procedure described for
String#count
on page 368. 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"
squeeze!
str.squeeze!(
[
aString
]*
)
->
str or
nil
Squeezes
str in place, returning either
str, or
nil if no changes were made.
strip
str.strip ->
aString
Returns a copy of
str with leading and trailing whitespace removed.
" hello ".strip
サ
"hello"
"\tgoodbye\r\n".strip
サ
"goodbye"
strip!
str.strip! ->
str or
nil
Removes leading and trailing whitespace from
str. Returns
nil if
str was not altered.
sub
str.sub(
pattern,
replacement )
->
aString
str.sub(
pattern ) {| match | block }
->
aString
Returns a copy of
str with the
first occurrence of
pattern replaced with either
replacement or the
value of the block. If the string form of the method is used,
special variables such as
$& will not be useful, as
substitution into the string occurs before the pattern match
starts. However, the sequences
1円,
2円,
listed in Table 22.7 on page 371 may be used.
In the block form, the current match is passed in as a
parameter, and variables such as
1ドル,
2ドル,
$`,
$&, and
$' will be set appropriately. The value returned by the block
will be substituted for the match on each call.
"hello".sub(/[aeiou]/, '*')
サ
"h*llo"
"hello".sub(/([aeiou])/, '<1円>')
サ
"h<e>llo"
"hello".sub('.') {|s| s[0].to_s + ' ' }
サ
"104 ello"
sub!
str.sub!(
pattern,
replacement )
->
str or
nil
str.sub!(
pattern ) {| match | block }
->
str or
nil
Performs the substitutions of
String#sub
in place,
returning
str, or
nil if no substitutions were
performed.
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
サ
"**+"
Equivalent to
String#succ
, but modifies the receiver in place.
sum
str.sum(
aFixnum=16 )
->
anInteger
Returns a basic
n-bit checksum of the characters in
str, where
n is the optional parameter, defaulting to 16. The
result is simply the sum of the binary value of each character
in
str modulo 2
n - 1. This is not a particularly good checksum.
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"
Equivalent to
String#swapcase
, but modifies the receiver in
place, returning
str, or
nil if no changes were
made.
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. The method never
raises an exception.
"123.45e1".to_f
サ
1234.5
"45.67 degrees".to_f
サ
45.67
"thx1138".to_f
サ
0.0
to_i
str.to_i ->
anInteger
Returns the result of interpreting leading characters in
str
as a decimal integer. 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. The method never
raises an exception.
"12345".to_i
サ
12345
"99 red balloons".to_i
サ
99
"0x0a".to_i
サ
0
"hello".to_i
サ
0
Returns the receiver.
Synonym for
String#to_s
.
to_str is
used by methods such as
String#concat
to convert their
arguments to a string. Unlike
to_s, which is supported
by almost all classes,
to_str is normally implemented
only by those classes that act like strings. Of the built-in
classes, only
Exception
and
String implement
to_str.
tr
str.tr(
fromString,
toString )
->
aString
Returns a copy of
str with the characters in
fromString replaced by the corresponding characters in
toString. If
toString is shorter than
fromString, it is padded with its last character. Both
strings may use the c
1--c
2 notation to denote ranges of
characters, and
fromString 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"
tr!
str.tr!(
fromString,
toString )
->
str or
nil
Translates
str in place, using the same rules as
String#tr
. Returns
str, or
nil if no changes were
made.
tr_s
str.tr_s(
fromString,
toString )
->
aString
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"
tr_s!
str.tr_s!(
fromString,
toString )
->
str or
nil
Performs
String#tr_s
processing on
str in place,
returning
str, or
nil if no changes were made.
unpack
str.unpack(
format )
->
anArray
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 Table 22.8 on page 379. Each directive may be
followed by a number, indicating the number of times to repeat
with this directive. An asterisk (``
*'') will use up all
remaining elements. The directives
sSiIlL may each be followed
by an underscore (``
_'') to use the underlying platform's
native size for the specified type; otherwise, it uses a
platform-independent consistent size. Spaces are ignored in the format
string. See also
Array#pack
on page 286.
Directives for
String#unpack
Format
Function
Returns
A
String with trailing nulls and spaces removed.
String
a
String.
String
B
Extract bits from each character (msb first).
String
b
Extract bits from each character (lsb first).
String
C
Extract a character as an unsigned integer.
Fixnum
c
Extract a character as an integer.
Fixnum
d
Treat sizeof(double) characters as a native
double.
Float
E
Treat sizeof(double) characters as a double in
little-endian byte order.
Float
e
Treat sizeof(float) characters as a float in
little-endian byte order.
Float
f
Treat sizeof(float) characters as a native float.
Float
G
Treat sizeof(double) characters as a double in
network byte order.
Float
g
Treat sizeof(float) characters as a float in
network byte order.
Float
H
Extract hex nibbles from each character (most
significant first).
String
h
Extract hex nibbles from each character (least
significant first).
String
I
Treat sizeof(int)
1 successive
characters as an unsigned native integer.
Integer
i
Treat sizeof(int)
1 successive
characters as a signed native integer.
Integer
L
Treat four1 successive
characters as an unsigned native
long integer.
Integer
l
Treat four1 successive
characters as a signed native
long integer.
Integer
M
Extract a quoted-printable string.
String
m
Extract a base64 encoded string.
String
N
Treat four characters as an unsigned long in network
byte order.
Fixnum
n
Treat two characters as an unsigned short in network
byte order.
Fixnum
P
Treat sizeof(char *) characters as a pointer, and
return len characters from the referenced location.
String
p
Treat sizeof(char *) characters as a pointer to a
null-terminated string.
String
S
Treat two1 successive characters as an unsigned
short in
native byte order.
Fixnum
s
Treat two1 successive
characters as a signed short in
native byte order.
Fixnum
U
Extract UTF-8 characters as unsigned integers.
Integer
u
Extract a UU-encoded string.
String
V
Treat four characters as an unsigned long in little-endian
byte order.
Fixnum
v
Treat two characters as an unsigned short in little-endian
byte order.
Fixnum
X
Skip backward one character.
---
x
Skip forward one character.
---
Z
String with trailing nulls removed.
String
@
Skip to the offset given by the length argument.
---
1 May be modified by appending ``_'' to the directive.
"abc 0円0円abc 0円0円".unpack('A6Z6')
サ
["abc", "abc "]
"abc 0円0円".unpack('a3a3')
サ
["abc", " 000円000円"]
"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"]
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"
Upcases the contents of
str, returning
nil if no
changes were made.
upto
str.upto(
aString )
{| s | block }
->
str
Iterates through successive values, starting at
str and
ending at
aString inclusive, passing each value in turn to
the block. The
String#succ
method is used to generate each
value.
"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
Extracted from the book "Programming Ruby -
The Pragmatic Programmer's Guide"
Copyright
©
2001 by Addison Wesley Longman, Inc. This material may
be distributed only subject to the terms and conditions set forth in
the Open Publication License, v1.0 or later (the latest version is
presently available at
http://www.opencontent.org/openpub/)).
Distribution of substantively modified versions of this document is
prohibited without the explicit permission of the copyright holder.
Distribution of the work or derivative of the work in any standard
(paper) book form is prohibited unless prior permission is obtained
from the copyright holder.