The String
class represents the arbitrary length of byte
string.
Some methods for the String
class which have the
name ends with `!', modify the contents of the strings.
The methods without `!' make copy of the string and
modify them. So, they are more slower but safer. For example:
f = "string" print f, f.sub("str", "ski"), f => string, skiing, string print f, f.sub!("str", "ski"), f => skiing, skiing, skiing
Object
Comparable
Enumerable
new(string)
Returns a newly created string object which has same contents to the string.
self + other
Returns newly created concatenated string.
self * times
Reputation of the string. For example, "x" * 4
returns
"xxxx"
.
self == other
self > other
self >= other
self < other
self <= other
String comparison. If the value of the variable $=
is
not false, comparison done by case-insensitive.
self === other
Same as operator `==
'. Used for case
comparison.
self =~ other
String match. Returns an index of the match if any, or nil
.
If the argument other is a string, it will be compiled into
a regular expression.
~ self
Same as $_ =~ self
.
self[nth]
Retrieves the nth character from a string.
self[start..last]
Returns a substring from start to last, including both ends.
self[start, length]
Returns a substring of length characters from start.
self[nth] = val
Changes the nth character of the string into val. If the strings is freezed, exception will occur.
self[start..last] = val
Replace the substring from start to last with val.
self[start, len] = val
self <=> other
Returns -1, 0, or 1 depending on whether the left argument is less than, equal to, or greater than the right argument in the dictionary order.
<<(other)
concat(other)
Appends the contents of the other.
capitalize
capitalize!
Changes the first character in the string to uppercase character, if it is an alphabet.
chop
chop!
Chops off the last character of the string (2 characters if the last
characters are "\r\n"). chop!
modifies the receiver.
crypt(salt)
Returns an encoded string using crypt(3). salt is the arbitrary string longer than 2 bytes.
delete(str)
delete!(str)
Deletes every characters included in str
from the
string. Deleting characters in str is in the form of
tr(1). For example, `a-c
' is the range from
`a' to `c', `^' at the
beginning means complement of the character set.
dup
Returns a newly created string object which has the save value to the
string. clone
returns the freezed string for the freezed
string. On the other hand, dup
copies the string
contents only.
downcase
downcase!
Replaces all uppercase characters to lowercase characters. Little bit
faster than tr("A-Z", "a-z")
.
each_byte {|char|...}
Iterates over each characters of the string.
each([rs]) {|line|...}
each_line([rs]) {|line|...}
Iterates over each line in the string. The value of the
rsis the line separator, which default is the value
of the variable $/
.
freeze
Prohibits modification of the string. Modification to the freezed string raises an exception.
frozen
Returns true if the string is frozen.
gsub(pattern, replace)
gsub!(pattern, replace)
Replaces all matching substrings with the pattern to the
replace. In replace, `&' and
`\0
' replaced to the matching substring, `\digit'
replaced to the contents of the corresponding parenthesis.
\`, \', and \+ replaced to
pre-match, post-match substring, and contents of the last parenthesis
respectively.
Notice: $<digits>
are not
available for the replace string, since it is evaluated
before, match happens.
The method gsub!
modifies the original string. If no
match found gsub!
returns nil
. On the other
hand, gsub
modifies the copy of the string. If no match
found, gsub
returns the unmodified original string.
gsub(pattern) {...}
gsub!(pattern) {...}
If gsub
and gsub!
called as an iterator,
replace all matching substring to the value of the iterator block.
The matching substring will be given to the iterator block.
hex
Interprets the string as a hexadecimal string and returns the corresponding integer value.
index(substr[, pos])
Returns the index of the substr in the string, or
nil
if not found. Optional second argument
pos is given, start lookup from there.
intern
Returns unique integer corresponding the string. The string must not contain the null character ('\0').
length
size
Returns the length of the string in bytes.
ljust(width)
rjust(width)
center(width)
Returns right filled, left filled, centered string, respectively. If the string is longer than width, returns the string itself without modification.
oct
Interprets the string as a octal string and returns the
corresponding integer value. Returns 0 if the string is not in
octal. The octal string is the pattern of
/^[0-7]+/
.
reverse
reverse!
Returns the reversed string of the original string.
rindex(substr[, pos])
Returns the index of the last occurrence of the substr, or
nil
if not found. If optional second argument
pos given, rindex
ends looking up there.
scan(pattern)
scan(pattern) {...}
Returns the array which contains subpatterns corresponding parentheses in the pattern. When called as an iterator, match will be done repeatedly to the end of the string. Subpatterns are passed to the iterator block as parameters.
split([sep[, limit]])
Return an array containing the fields of the string, using the string
sep as a separator. If sep is omitted, the
value of the variable $;
will be used as default. If the
value of $;
is nil
, splits the string on
whitespace (after skipping any leading whitespace). Anything matching
pattern is taken to be a delimiter separating the fields.
(Note that the delimiter may be longer than one character.)
If limit is specified and is not negative, splits into no more than that many fields (though it may split into fewer).
A pattern matching the null string (not to be confused with a null
pattern //
, which is just one member of the set of
patterns matching a null string) will split the string into separate
characters at each point it matches that way. For example:
produces the output 'h:i:t:h:e:r:e'.print 'hi there'.split(/ */).join(':');
squeeze([str])
squeeze!([str])
Squeezes sequences of the same characters which is included in the str.
strip
strip!
Removes leading and trailing whitespace from the string.
sub(pattern, replace)
sub!(pattern, replace)
Replaces the first matching substrings with the pattern to
the replace. In replace, `&'
and `\0
' replaced to the matching substring, `\digit'
replaced to the contents of the corresponding parenthesis.
Notice: $<digits>
are not
available for the replace string, since it is evaluated
before, match happens.
The method sub!
modifies the original string. If no
match found, sub!
returns nil
. On the other
hand, sub
modifies the copy of the string. If no match
found, sub
returns the unmodified original string.
sub(pattern) {...}
sub!(pattern) {...}
If gsub
and gsub!
called as an iterator,
replace the first matching substring to the value of the iterator
block. You can use $<digits>
in the iterator
block, for the block is evaluated after the match.
The matching substring will be given to the iterator block.
succ
Returns the succeeding string from self
,
which is like:
"aa".succ => "ab" "99".succ => "100" "a9".succ => "b0" "Az".succ => "Ba" "zz".succ => "aaa"
sum([bits])
Calculates bits-bit checksum of the string. Default is 16-bit checksum. For example, the following computes the same number as the System V sum program:
while gets sum += $_.sum end sum %= 65536
swapcase
swapcase!
Replaces all lowercase characters to uppercase characters, and all uppercase characters to lowercase characters.
to_f
Converts the string into Float
.
to_i
Interprets the string as a decimal string and returns the corresponding integer value.
tr(search, replace)
tr!(search, replace)
Translates all occurrences of the characters found in search,
with the corresponding character in replace. The first
character in the search is `^
', characters not
in the search are translated.
There is the method tr_s(src,repl)
to do
str.tr(src,repl).squeeze(repl)
for convenience.
unpack(template)
Unpacks packed string data (probably made by
Array#pack
), and expanded
array value. The template has the same format as in the
Array#pack
, as follows this:
a
- ASCII string(null padded)
A
- ASCII string(space padded)
b
- bit string(ascending bit order)
B
- bit string(descending bit order)
h
- hex string(low nibble first)
H
- hex string(high nibble first)
c
- char
C
- unsigned char
s
- short
S
- unsigned short
i
- int
I
- unsigned int
l
- long
L
- unsigned int
n
- short in "network" byte-order
N
- long in "network" byte-order
v
- short in "VAX" (little-endian) byte-order
V
- long in "VAX" (little-endian) byte-order
f
- single-precision float in the native format
d
- A double-precision float in the native format
u
- uuencoded string
x
- skip a byte
X
- back up a byte
@
- moves to absolute position
upcase
upcase!
Replaces all lowercase characters to downcase characters. Little bit
faster than tr("a-z", "A-Z")
.
upto(max) {...}
Iterates from self
to max, giving the
next string each time.
(See succ
)
This method used internally in
Range#each
,
that makes
print `a, b, c,...z,aa,...az, ba'.for i in "a" .. "ba" print i, "\n" end