Website hosting service by Active-Venture.com
 

 Back to Index

prev - up - next - index

String

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

SuperClass:

Object

Included Modules:

Comparable
Enumerable

Class Methods:

new(string)

Returns a newly created string object which has same contents to the string.

Methods:

self + other

Returns newly created concatenated string.

self * times

Reputation of the string. For example, "x" * 4 returns "xxxx".

self % args

Formats from the string. Works just like: sprintf(self, *args).

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

Appends other's value to the string contents.

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

Replace the substring length characters from start with 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.

capitalize! returns nil, if it does not modify the receiver.

chop
chop!

Chops off the last character of the string (2 characters if the last characters are "\r\n"). chop! modifies the receiver.

chop! returns nil, if it does not modify the receiver.

chomp([rs])
chomp!([rs])

Chops off the line ending of the string, which is specified by the rs. The default value of the rs is the value of the variable $/.

chomp! modifies the receiver, and returns nil, if it does not modify the receiver.

clone
dup

Returns a newly created string object which has the save value to the string. clone returns the complete copy of the original string including freeze status and instance variables. On the other hand, dup copies the string contents only.

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.

delete! returns nil, if it does not modify the receiver.

downcase
downcase!

Replaces all uppercase characters to lowercase characters. Little bit faster than tr("A-Z", "a-z").

downcase! returns nil, if it does not modify the receiver.

dump

Replaces all non-printable characters into backslash notations. The condition str == eval(str.dump) is guaranteed.

each_byte {|byte|...}

Iterates over each byte 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 $/.

empty?

Returns true, if the string is empty (i.e. 0 length string).

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! are called with the block, replace all matching substring to the value of the block. The matching substring will be given to the 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 left filled, right 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.

replace(other)

Copis the content of other into the 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 returns the last occurrence at or before that position.

scan(pattern)
scan(pattern) {...}

Returns the array of arrays which contain subpatterns corresponding parentheses in the pattern. Match will be done repeatedly to the end of the string. When called with the block, subpatterns are passed to the block as parameters.

split([sep[, limit]])

Return an array containing the fields of the string, using the string or regexp 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 sep is taken to be a delimiter separating the fields. (Note that the delimiter may be longer than one character.)

If limit is unspecified, trailing null fields are stripped (which potential users of pop() would do well to remember). If limit is specified and is not negative, splits into no more than that many fields (though it may split into fewer). If limit is negative, it is treated as if an arbitrarily large limit had been specified.

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:

print 'hi there'.split(/ */).join(':');

produces the output 'h:i:t:h:e:r:e'.

squeeze([str])
squeeze!([str])

Squeezes sequences of the same characters which is included in the str.

squeezes! returns nil, if it does not modify the receiver.

strip
strip!

Removes leading and trailing whitespace from the string.

strip! returns nil, if it does not modify the receiver.

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! are called with the block, replace the first matching substring to the value of the 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 block.

succ
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:

sum = 0
while gets
  sum += $_.sum
end
sum %= 65536

swapcase
swapcase!

Replaces all lowercase characters to uppercase characters, and all uppercase characters to lowercase characters.

swapcase! returns nil, if it does not modify the receiver.

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.

tr! returns nil, if it does not modify the receiver.

tr_s(search, replace)
tr_s!(search, replace)

Translates all occurrences of the characters found in search, with the corresponding character in replace, then squeezes sequences of the same characters within the replaced characters. The first character in the search is `^', characters not in the search are translated.

tr_s! returns nil, if it does not modify the receiver.

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 long
m
string encoded in base64
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
p
A pointer to a null-terminated string.
P
A pointer to a structure (fixed-length string).
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").

upcase! returns nil, if it does not modify the receiver.

upto(max) {...}

Iterates from self to max, giving the next string each time. (See succ) This method used internally in Range#each, that makes

     for i in "a" .. "ba"
       print i, "\n"
     end

print `a, b, c,...z,aa,...az, ba'.


prev - up - next - index

matz@netlab.co.jp

 

  

 

 

2002-2004 Active-Venture.com Website Hosting Service

 
Buy domain name at only $5.95/yr with comprehensive domain hosting services. Domain registration and domain search service from $5.95 Cheap domain name registration and domain transfer service
 

Disclaimer: This documentation is provided only for the benefits of our website hosting customers.
For authoritative source of the documentation, please refer to http://www.ruby-doc.org/docs/