Ruby Strings (String)
String objects in Ruby are used to store or manipulate a sequence of one or more bytes.
Ruby strings are divided into single-quoted strings (') and double-quoted strings ("), the difference being that double-quoted strings support more escape characters.
Single-Quoted Strings
The simplest string is a single-quoted string, that is, a string placed within single quotes:
'
This is a string in a Ruby program
'
If you need to use a single-quote character inside a single-quoted string, you need to use a backslash () in the single-quoted string, so that the Ruby interpreter does not consider this single-quote character as the end of the string:
'
Won
'
t you read O
'
Reilly
'
s book?
'
A backslash can also escape another backslash, so that the second backslash itself is not interpreted as an escape character.
The following are string-related features in Ruby.
Double-Quoted Strings
In double-quoted strings we can use #{} the hash sign and curly braces to compute the value of expressions:
Embed variables in a string:
Example
!/usr/bin/ruby
-- coding: UTF-8 --
name1
=
"
Joe
"
name2
=
"
Mary
"
puts
"
Hello #{name1}, #{name2} where are you?
"
Try it »
The output of the above example is:
你好 Joe, Mary 在哪?
Performing mathematical operations in a string:
Example
!/usr/bin/ruby
-- coding: UTF-8 --
x
,
y
,
z
=
12
,
36
,
72
puts
"
The value of x is #{ x }
"
puts
"
The value of x + y is #{ x + y }
"
puts
"
The average of x + y + z is #{ (x + y + z)/3 }
"
Try it »
The output of the above example is:
x 的值为 12
x + y 的值为 48
x + y + z 的平均值为 40
Ruby also supports a kind of string literal introduced with %q and %Q. %q uses single-quote quoting rules, while %Q uses double-quote quoting rules, followed by an opening delimiter such as (! [ { and a corresponding closing delimiter such as } ] ).
The character following q or Q is the delimiter. The delimiter can be any non-alphanumeric single-byte character, such as [, {, (,<, ! etc. The string is read until a matching closing delimiter is found.
Example
!/usr/bin/ruby
-- coding: UTF-8 --
desc1
=
%Q{
Ruby strings can use '' and "".
}
desc2
=
%q|
Ruby strings can use '' and "".
|
puts
desc1
puts
desc2
Try it »
The output of the above example is:
Ruby 的字符串可以使用 '' 和 ""。
Ruby 的字符串可以使用 '' 和 ""。
Escape character
The table below lists escape characters or non-printable characters that can be escaped using the backslash symbol.
**Note:** Within a string enclosed in double quotes, escape characters are interpreted. Within a string enclosed in single quotes, escape characters are not interpreted and are output as-is.
| Backslash symbol | Hexadecimal character | Description |
|---|---|---|
| \a | 0x07 | Alarm (bell) character |
| \b | 0x08 | Backspace |
| \cx | Control-x | |
| \C-x | Control-x | |
| \e | 0x1b | Escape Character |
| \f | 0x0c | Form feed |
| \M-\C-x | Meta-Control-x | |
| \n | 0x0a | Newline |
| \nnn | Octal notation, where n ranges from 0.7 | |
| \r | 0x0d | Carriage return |
| \s | 0x20 | Whitespace character |
| \t | 0x09 | Tab |
| \v | 0x0b | Vertical tab |
| \x | Character x | |
| \xnn | Hexadecimal notation, where n ranges from 0.9, a.f, or A.F |
: This method loads the entire file content into memory, so it is not suitable for processing large files
Ruby's default character set is ASCII, where characters can be represented by a single byte. If you use UTF-8 or other modern character sets, characters may be represented by one to four bytes.
You can change the character set at the beginning of your program using $KCODE, as shown below:
$KCODE = 'u'
The following are possible values of $KCODE.
| Encoding | Description |
|---|---|
| a | ASCII (same as none). This is the default. |
| e | EUC。 |
| n | None (same as ASCII). |
| u | UTF-8。 |
String Built-in Methods
We need an instance of a String object to call String methods. The following are ways to create a String object instance:
new
[
String
.
new
(
str
=
"
"
)
]
This returns a new string object containing a copy of str Now, using the str object, we can call any available instance method. For example:
Example
!/usr/bin/ruby
myStr
=
String
.
new
(
"
THIS IS TEST
"
)
foo
=
myStr
.
downcase
puts
"
#{foo}
"
This will produce the following result:
this is test
The following are public string methods (assuming str is a String object):
| No. | Method & Description |
|---|---|
| 1 | str % arg |
| Formats a string using format specifications. If arg contains more than one substitution, then arg must be an array. For more information about format specifications, see sprintf under the "Kernel Module". | |
| 2 | str * integer |
| Returns a new string consisting of integer copies of str. In other words, str is repeated integer times. | |
| 3 | str + other_str |
| Concatenates other_str to str. | |
| 4 | str << obj |
| Appends an object to a string. If the object is a Fixnum in the range 0.255, it is converted to a character. Compare it with concat. | |
| 5 | str <=> other_str |
| Compares str with other_str, returning -1 (less than), 0 (equal), or 1 (greater than). The comparison is case-sensitive. | |
| 6 | str == obj |
| Checks the equality of str and obj. Returns false if obj is not a string, and returns true if str <=> obj, returning 0. | |
| 7 | str =~ obj |
| Matches str against the regular expression pattern obj. Returns the position where the match begins, or false otherwise. | |
| 8 | **str[position] # note that this returns the ASCII code, not the character |
str[start, length]
str[start..end]
str[start...end]**
Extracts a substring using an index | | 9 | str.capitalize
Converts the first letter of the string to uppercase and the rest to lowercase. | | 10 | str.capitalize!
Same as capitalize, but returns nil if no changes were made. | | 11 | str.casecmp
Case-insensitive string comparison. | | 12 | str.center
Centers the string. | | 13 | str.chomp
Removes the record separator ($/) from the end of the string, usually \n. If there is no record separator, nothing is done. | | 14 | str.chomp!
Same as chomp, but str is modified in place and returned. | | 15 | str.chop
Removes the last character from str. | | 16 | str.chop!
Same as chop, but str is modified in place and returned. | | 17 | str.concat(other_str)
Concatenates other_str to str. | | 18 | str.count(str, ...)
Counts one or more sets of characters. If there are multiple sets, counts the intersection of these sets. | | 19 | str.crypt(other_str)
Applies a one-way cryptographic hash to str. The argument is a two-character string, each character ranging over a.z, A.Z, 0.9, ., or /. | | 20 | str.delete(other_str, ...)
Returns a copy of str with all characters in the intersection of the arguments removed. | | 21 | str.delete!(other_str, ...)
Same as delete, but str is modified in place and returned. | | 22 | str.downcase
Returns a copy of str with all uppercase letters replaced with lowercase letters. | | 23 | str.downcase!
Same as downcase, but str is modified in place and returned. | | 24 | str.dump
Returns a version of str with all non-printable characters replaced with \nnn notation and all special characters escaped. | | 25 | str.each(separator=$/) { |substr| block }
Divides str using the argument as the record separator (default is $/) and passes each substring to the supplied block. | | 26 | str.each_byte { |fixnum| block }
Passes each byte of str to the block, returning each byte in decimal notation. | | 27 | str.each_line(separator=$/) { |substr| block }
Divides str using the argument as the record separator (default is $/) and passes each substring to the supplied block. | | 28 | str.empty?
Returns true if str is empty (that is, has a length of 0). | | 29 | str.eql?(other)
Two strings are equal if they have the same length and content. | | 30 | str.gsub(pattern, replacement) [or]
str.gsub(pattern) { |match| block }
Returns a copy of str with all occurrences of pattern replaced with replacement or the value of the block. pattern is typically a regular expression Regexp; if it is a String, no regular expression metacharacters are interpreted (that is, /\d/ will match a digit, but '\d' will match a backslash followed by a 'd'). | | 31 | str[fixnum] [or] str[fixnum,fixnum] [or] str[range] [or] str[regexp] [or] str[regexp, fixnum] [or] str[other_str]
References str using the following arguments: if the argument is a Fixnum, returns the character code of the fixnum; if the arguments are two Fixnums, returns a substring starting at the offset (the first fixnum) and spanning up to the length (the second fixnum); if the argument is a range, returns a substring within that range; if the argument is a regexp, returns the part of the string that matches; if the argument is a regexp with a fixnum, returns the match data at the fixnum position; if the argument is an other_str, returns the substring matching other_str. A negative Fixnum counts from the end of the string, starting at -1. | | 32 | str[fixnum] = fixnum [or] str[fixnum] = new_str [or] str[fixnum, fixnum] = new_str [or] str[range] = aString [or] str[regexp] =new_str [or] str[regexp, fixnum] =new_str [or] str[other_str] = new_str ]
Replaces the entire string or part of the string. Synonymous with slice!. | | 33 | str.gsub!(pattern, replacement) [or] str.gsub!(pattern) { |match| block }
Performs the substitution of String#gsub, returning str, or nil if no substitution was performed. | | 34 | str.hash
Returns a hash based on the string's length and content. | | 35 | str.hex
Treats the leading characters of str as a string of hexadecimal digits (an optional sign and an optional 0x) and returns the corresponding number. Returns zero on error. | | 36 | str.include? other_str [or] str.include? fixnum
Returns true if str contains the given string or character. | | 37 | str.index(substring [, offset]) [or]
str.index(fixnum [, offset]) [or]
str.index(regexp [, offset])
Returns the index of the first occurrence of the given substring, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If a second argument is provided, it specifies the position in the string at which to begin searching. | | 38 | str.insert(index, other_str)
Inserts other_str before the character at the given index, modifying str. A negative index counts from the end of the string and inserts after the given character. The intent is to begin inserting a string at the given index. | | 39 | str.inspect
Returns the printable version of str, with special characters escaped. | | 40 | str.intern [or] str.to_sym
Returns the symbol corresponding to str, creating the symbol if it did not previously exist. | | 41 | str.length
Returns the length of str. Compare it with size. | | 42 | str.ljust(integer, padstr=' ')
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. | | 43 | str.lstrip
Returns a copy of str with leading whitespace removed. | | 44 | str.lstrip!
Removes leading whitespace from str, returning nil if no changes were made. | | 45 | str.match(pattern)
If pattern is not a regular expression, converts pattern to a Regexp and then calls its match method on str. | | 46 | str.oct
Treats the leading characters of str as a string of decimal digits (an optional sign) and returns the corresponding number. Returns 0 if the conversion fails. | | 48 | str.replace(other_str)
Replaces the contents of str with the corresponding values in other_str. | | 49 | str.reverse
Returns a new string that is the reverse of str. | | 50 | str.reverse!
Reverses str in place, modifying and returning str. | | 51 | str.rindex(substring [, fixnum]) [or]
str.rindex(fixnum [, fixnum]) [or]
str.rindex(regexp [, 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 a second argument is provided, it specifies the position in the string at which to end the search. Characters beyond that point are not considered. | | 52 | str.rjust(integer, padstr=' ')
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. | | 53 | str.rstrip
Returns a copy of str with trailing whitespace removed. | | 54 | str.rstrip!
Removes trailing whitespace from str, returning nil if no changes were made. | | 55 | str.scan(pattern) [or]
str.scan(pattern) { |match, ...| block }
Both forms iterate over 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 an array containing one entry per group. | | 56 | str.slice(fixnum) [or] str.slice(fixnum, fixnum) [or]
str.slice(range) [or] str.slice(regexp) [or]
str.slice(regexp, fixnum) [or] str.slice(other_str)
See str[fixnum], etc.
str.slice!(fixnum) [or] str.slice!(fixnum, fixnum) [or] str.slice!(range) [or] str.slice!(regexp) [or] str.slice!(other_str)
Deletes the specified portion from str and returns the deleted portion. If the value is out of range, the form with a Fixnum argument generates an IndexError. The form with a range argument generates a RangeError, while the forms with Regexp and String arguments ignore the operation. | | 57 | str.split(pattern=$;, [limit])
Divides str into substrings based on a separator and returns an array of these substrings.
If both the pattern is a String, then when splitting str, it is used as the separator. If pattern is a single space, then str is split on whitespace, ignoring leading whitespace and consecutive whitespace characters.
If both the pattern is a regular expression Regexp, then str is split wherever pattern matches. When pattern matches a zero-length string, str is split into individual characters.
If omitted, the pattern argument, the value of $; is used. If $; is nil (the default), str is split on whitespace as if it had been specified as the separator.
If omitted, the limit argument suppresses trailing null fields. If limit is a positive number, at most that many fields are returned (if limit is 1, the entire string is returned as the only entry in the array). If limit is negative, there is no limit on the number of fields returned, and trailing null fields are not suppressed.
| | 57 | str.squeeze([other_str]*)Builds a set of characters from the other_str arguments using the procedure described for String#count. Returns a new string in which identical characters occurring in the set are replaced with a single character. If no arguments are given, all identical characters are replaced with a single character. | | 58 | str.squeeze!([other_str]*)
Same as squeeze, but str is modified in place and returned, or nil if no changes were made. | | 59 | str.strip
Returns a copy of str with leading and trailing whitespace removed. | | 60 | str.strip!
Removes leading and trailing whitespace from str, returning nil if no changes were made. | | 61 | str.sub(pattern, replacement) [or]
str.sub(pattern) { |match| block }
Returns a copy of str with the first occurrence of pattern replaced with replacement or the value of the block. pattern is typically a regular expression Regexp; if it is a String, no regular expression metacharacters are interpreted. | | 62 | str.sub!(pattern, replacement) [or]
str.sub!(pattern) { |match| block }
Performs the substitution of String#sub and returns str, or nil if no substitution was performed. | | 63 | str.succ [or] str.next
Returns the successor of str. | | 64 | str.succ! [or] str.next!
Equivalent to String#succ, but str is modified in place and returned. | | 65 | str.sum(n=16)
Returns the n-bit checksum of characters in str, where n is an optional Fixnum argument defaulting to 16. The result is simply the sum of the binary values of each character in str modulo 2n - 1. This is not a particularly good checksum. | | 66 | str.swapcase
Returns a copy of str with all uppercase letters converted to lowercase and all lowercase letters converted to uppercase. | | 67 | str.swapcase!
Equivalent to String#swapcase, but str is modified in place and returned, or nil if no changes were made. | | 68 | str.to_f
Returns the result of interpreting the leading characters of str as a floating-point number. Extra characters beyond the end of the valid number are ignored. If there is no valid number at the beginning of str, 0.0 is returned. This method does not raise an exception. | | 69 | str.to_i(base=10)
Returns the result of interpreting the leading characters of str as an integer in base (base 2, 8, 10, or 16). Extra characters beyond the end of the valid number are ignored. If there is no valid number at the beginning of str, 0 is returned. This method does not raise an exception. | | 70 | str.to_s [or] str.to_str
Returns the value received. | | 71 | str.tr(from_str, to_str)
Returns a copy of str with characters from 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 can use the c1.c2 notation to indicate a range of characters. If from_str begins with ^, it means all characters except those listed. | | 72 | str.tr!(from_str, to_str)
Equivalent to String#tr, but str is modified in place and returned, or nil if no changes were made. | | 73 | str.tr_s(from_str, to_str)
Processes str according to the rules described for String#tr, then removes duplicate characters that would be affected by the translation. | | 74 | str.tr_s!(from_str, to_str)
Equivalent to String#tr_s, but str is modified in place and returned, or nil if no changes were made. | | 75 | str.unpack(format)
Decodes str (which may contain binary data) according to the format string, returning an array of each extracted value. The format string consists of a series of single-character directives. Each directive may be followed by a number indicating how many times to repeat that directive. An asterisk (*) will use all remaining elements. Each of the directives sSiIlL may be followed by an underscore (_) to use the native size of the specified type for the underlying platform; otherwise a platform-independent consistent size is used. Spaces in the format string are ignored. | | 76 | str.upcase
Returns a copy of str with all lowercase letters replaced with uppercase letters. The operation is locale-insensitive; only the characters a to z are affected. | | 77 | str.upcase!
Changes the contents of str to uppercase, returning nil if no changes were made. | | 78 | str.upto(other_str) { |s| block }
Iterates over successive values, starting with str and ending with other_str (inclusive), passing each value in turn to the block. The String#succ method is used to generate each value. |
String unpack Directives
The following table lists the unpack directives for the String#unpack method.
| Instruction | Return | Description |
|---|---|---|
| A | String | Removes trailing nulls and spaces. |
| a | String | The string. |
| B | String | Extracts bits from each character (most significant bit first). |
| b | String | Extracts bits from each character (least significant bit first). |
| C | Fixnum | Extracts a character as an unsigned integer. |
| c | Fixnum | Extracts a character as an integer. |
| D, d | Float | Treats sizeof(double) characters as a native double. |
| E | Float | Treats sizeof(double) characters as a double in little-endian byte order. |
| e | Float | Treats sizeof(float) characters as a float in little-endian byte order. |
| F, f | Float | Treats sizeof(float) characters as a native float. |
| G | Float | Treats sizeof(double) characters as a double in network byte order. |
| g | Float | Treats sizeof(float) characters as a float in network byte order. |
| H | String | Extracts hexadecimal from each character (most significant bit first). |
| h | String | Extracts hexadecimal from each character (least significant bit first). |
| I | Integer | Treats sizeof(int) characters (modified by _) as a native integer. |
| i | Integer | Treats sizeof(int) characters (modified by _) as a signed native integer. |
| L | Integer | Treats four characters (modified by _) as an unsigned native long integer. |
| l | Integer | Treats four characters (modified by _) as a signed native long integer. |
| M | String | Quoted-printable. |
| m | String | Base64 encoded. |
| N | Integer | Treats four characters as an unsigned long in network byte order. |
| n | Fixnum | Treats two characters as an unsigned short in network byte order. |
| P | String | Treats sizeof(char *) characters as a pointer and returns \emph{len} characters from the referenced location. |
| p | String | Treats sizeof(char *) characters as a pointer to a null-terminated string. |
| Q | Integer | Treats eight characters as an unsigned quad word (64 bits). |
| q | Integer | Treats eight characters as a signed quad word (64 bits). |
| S | Fixnum | Treats two characters (different if _ is used) as an unsigned short in native byte order. |
| s | Fixnum | Treats two characters (different if _ is used) as a signed short in native byte order. |
| U | Integer | UTF-8 character, as an unsigned integer. |
| u | String | UU encoded. |
| V | Fixnum | Treats four characters as an unsigned long in little-endian byte order. |
| v | Fixnum | Treats two characters as an unsigned short in little-endian byte order. |
| w | Integer | BER-compressed integer. |
| X | Skips backward one character. | |
| x | Skips forward one character. | |
| Z | String | Used with *, removes trailing nulls until the first null. |
| @ | Skips the offset given by the length argument. |
Example
Try the following example to unpack various kinds of data.
"
abc
\0
\0
abc
\0
\0
"
.
unpack
(
'
A6Z6
'
)
=> ["abc", "abc "]
"
abc
\0
\0
"
.
unpack
(
'
a3a3
'
)
=> ["abc", " \000\000"]
"
abc
\0
abc
\0
"
.
unpack
(
'
ZZ
'
)
=> ["abc ", "abc "]
"
aa
"
.
unpack
(
'
b8B8
'
)
=> ["10000110", "01100001"]
"
aaa
"
.
unpack
(
'
h2H2c
'
)
=> ["16", "61", 97]
"
\x
fe
\x
ff
\x
fe
\x
ff
"
.
unpack
(
'
sS
'
)
=> [-2, 65534]
"
now=20is
"
.
unpack
(
'
M*
'
)
=> ["now is"]
"
whole
"
.
unpack
(
'
xax2aX2aX1aX2a
'
)
=> ["h", "e", "l", "l", "o"]