home PYTHONJAVA
 

Ruby String(String)

The String object in Ruby is used to store or manipulate a sequence of one or more bytes.

Ruby strings are divided into single quoted strings (') and double quoted strings ("), except that double quoted strings can support more escape characters.

Single quote string

The simplest string is a single quoted string, which stores the string in single quotes:

'This is a string of Ruby programs'

If you need to use single quote characters in a single quoted string, you need to use a backslash (\) in a single quoted string so that the Ruby interpreter does not consider the single quote character to be the string's termination symbol. :

'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 string

In double quoted strings we can use #{} hashes and braces to calculate the value of an expression:

Embedded variables in strings:

Instance

#!/usr/bin/ruby # -*- coding: UTF-8 -*- name1 = "Joe" name2 = "Mary" puts "Hello there #{name1}, #{name2} where?"

The output of the above example output is:

Hello Joe, Mary Where?

Mathematical operations in strings:

Instance

Instance

#!/usr/bin/ruby # -*- coding: UTF-8 -*- x, y, z = 12, 36, 72 puts "x Value #{ x }" puts "x + y Value #{ x + y }" puts "x + y + z Value #{ (x + y + z)/3 }"

The output of the above example output is:

x Value 12
x + y Value 48
x + y + z The average value is 40

Ruby also supports a string variable that uses %q and %Q to boot, %q uses a single quote quote rule, and %Q is a double quote quote rule, followed by one (! [ { etc. The delimiter and the end delimiter of }] and so on.

The character following q or Q is the delimiter. The delimiter can be any non-alphanumeric single-byte character. For example: [,{,(,<,! etc., the string will be read until the phase is found. The ending term of the match.

Instance

#!/usr/bin/ruby # -*- coding: UTF-8 -*- desc1 = %Q{Ruby String can be used '' with ""。} desc2 = %q|Ruby String can be used '' with ""。| puts desc1 puts desc2

The above example output output output is:

Ruby String can be used '' with ""
Ruby String can be used '' with ""

escape characters

The

subscript lists escaped or non-printable characters that can be escaped with a backslash symbol.

Note: In a string enclosed in double quotes, the escape character will be parsed. In a string enclosed in single quotes, the escape character will not be parsed and will be output as is.

backslash symbolhexadecimal charactersdescription
\a0x07Alarms
\b0x08Backspace
\cx Control-x
\C-x Control-x
\e0x1bescapes
\f0x0cpage break
\M-\C-x Meta-Control-x
\n0x0aLine breaks
\nnn octal notation, where n ranges from 0.7
\r0x0dCarriage Return
\s0x20space character
\t0x09tabs
\v0x0bVertical Tabs
\x character x
\xnn hexadecimal notation, where n ranges from 0.9, a.f or A.F

character encoding

Ruby's default character set is ASCII, and characters can be represented in a single byte. If you use UTF-8 or other modern character sets, the characters may be represented by one to four bytes.

You can change the character set using $KCODE at the beginning of the program as follows:

$KCODE = 'u'

The following are possible values for $KCODE.

EncodingDescription
aASCII (same as none). This is the default.
eEUC.
nNone (same as ASCII).
uUTF-8.

String built-in method

We need to have an instance of a String object to call the String method. Here's how to create an instance of a String object:

new [ String.new< Span class="hl-brackets">(str="")]

This will return a new string object containing a copy of str. Now, with the str object, we can call any of the available instance methods. For example:

Instance

#!/usr/bin/ruby myStr = String.new("THIS IS TEST") foo = myStr.downcase puts "#{foo}"

This will produce the following results:

this is test

The following is a public string method (assuming str is a String object):

serial numbermethod & description
1str % arg
Format the string using the format specification. If arg contains more than one substitution, then arg must be an array. For more information on format specifications, check out sprintf under "Core Modules."
2str * integer
returns a new string containing integer str . In other words, str is repeated integer times.
3str + other_str
Connect other_str to str.
4str << obj
Connect an object to a string. If the object is a fixed number Fixnum with a range between 0.255, it is converted to a character. Compare it to concat.
5str <=> other_str
Compare str with other_str and return -1 (less than), 0 (equal) or 1 (greater than). The comparison is case sensitive.
6str == obj
Check the equality of str and obj. Returns false if obj is not a string, true if str <=> obj, returns 0.
7str =~ obj
According to the regular expression pattern obj matches str. Returns the position where the match started, otherwise returns false.
8str[position] # Note that the ASCII code is returned instead of the character
Str[start, length]
Str[start..end]
Str[start...end]

Use an index to intercept a substring
9str.capitalize
Converts a string to an uppercase letter.
10str.capitalize!
Same as capitalize, but str will change and return.
11str.casecmp
Case-insensitive string comparison.
12str.center
Centered string.
13str.chomp
Remove the record separator ($/) from the end of the string, usually \n. If no separator is recorded, no action is taken.
14str.chomp!
Same as chomp, but str will change and return.
15str.chop
Remove the last character in str.
16str.chop!
Same as chop, but str will change and return.
17str.concat(other_str)
Connect other_str to str.
18str.count(str, ...)
Count one or more character sets. If there are multiple character sets, the intersection of these sets is counted.
19str.crypt(other_str)
Applies a one-way cryptographic hash to str. The argument is a two-character string of characters, each of which has a range of a.z, A.Z, 0.9, . or /.
20str.delete(other_str, ...)
Returns a copy of str, and all characters in the parameter intersection are deleted.
21str.delete!(other_str, ...)
Same as delete, but str will change and return.
22str.downcase
Returns a copy of str, and all uppercase letters are replaced with lowercase letters.
23str.downcase!
Same as downcase, but str will change and return.
24str.dump
returns the version of str, all non-printing characters are replaced with \nnn symbols, all special characters are transferred Righteousness.
25str.each(separator=$/) { |substr| block }
Use parameters as record separators (default is $/ Separate str, passing each substring to the provided block.
26str.each_byte { |fixnum| block }
Pass each byte of str to the block, in decimal notation of bytes Returns each byte.
27str.each_line(separator=$/) { |substr| block }
Use parameters as record separators (default is $/ Separate str, passing each substring to the provided block.
28str.empty?
Returns true if str is empty (ie, length is 0).
29str.eql?(other)
If two strings have the same length and content, then the two strings are equal .
30str.gsub(pattern, replacement) [or]
Str.gsub(pattern) { |match| block }

Returns a copy of str, with all occurrences of pattern replaced with the value of replacement or block. Pattern is usually a regular expression Regexp; if it is a string String, no regular expression metacharacters are interpreted (ie, /\d/ will match a number, but '\d' will match a backslash followed by a 'd').
31str[fixnum] [or] str[fixnum,fixnum] [or] str[range] [or] str[regexp] [or] str[regexp , fixnum] [or] str[other_str]
Use the following parameters to reference str: the parameter is a Fixnum, which returns the character encoding of fixnum; if the parameter is two Fixnum, it returns a slave offset (the first) A fixnum) starts the substring up to the length (the second fixnum); if the argument is range, it returns a substring within the range; if the argument is regexp, it returns the part matching the string; The regexp with fixnum returns the matching data of the fixnum position; if the parameter is other_str, it returns the substring matching other_str. A negative Fixnum starts at the end of the string -1.
32str[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 ]
Replace the entire string or part of the string. Synonymous with slice!
33str.gsub!(pattern, replacement) [or] str.gsub!(pattern) { |match| block }
Execution Replaces String#gsub, returns str, and returns nil if no replacement is performed.
34str.hash
Returns a hash based on the length and content of the string.
35str.hex
treats the leading character of str as a string of hexadecimal digits (an optional symbol and a Optional 0x) and return the corresponding number. Returns zero if it is an error.
36str.include? other_str [or] str.include? fixnum
If str contains the given string or character, then return True.
37str.index(substring [, offset]) [or]
Str.index(fixnum [, offset]) [or]
Str.index(regexp [, offset])

Returns the index of the first occurrence of a given string, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second argument is supplied, specifies where to start the search in the string.
38str.insert(index, other_str)
Insert other_str before the character of the given index, modify str. A negative index starts counting from the end of the string and is inserted after the given character. The intent is to start inserting a string at a given index.
39str.inspect
Returns a printable version of str with special characters that are escaped.
40str.intern [or] str.to_sym
Returns the symbol corresponding to str and creates a symbol if it does not exist before.
41str.length
returns the length of str. Compare it to size.
42str.ljust(integer, padstr=' ')
If the integer is greater than the length of str, return a new character of length integer String, the new string is left-aligned with str and padded with padstr. Otherwise, return str.
43str.lstrip
Returns a copy of str, removing leading spaces.
44str.lstrip!
Remove the leading spaces from str and return nil if there are no changes.
45str.match(pattern)
If pattern is not a regular expression, convert pattern to regular expression Regexp, then in str Call its matching method on it.
46str.oct
treats the leading character of str as a string of decimal digits (an optional symbol) and returns the phase The corresponding number. Returns 0 if the conversion failed.
47str.replace(other_str)
Replace the contents of str with the corresponding value in other_str.
48str.reverse
Returns a new string, which is the reverse of str.
49str.reverse!
Reverse str, str will change and return.
50str.rindex(substring [, fixnum]) [or]
Str.rindex(fixnum [, fixnum]) [or]
Str.rindex(regexp [, fixnum])

Returns the index of the last occurrence of a given string, character (fixnum), or pattern (regexp) in str. Returns nil if not found. If the second argument is supplied, specifies where to end the search in the string. Characters beyond this point will not be considered.
51str.rjust(integer, padstr=' ')
If the integer is greater than the length of str, return a new character of length integer String, the new string is right-aligned with str and padded with padstr. Otherwise, return str.
52str.rstrip
Returns a copy of str, removing trailing spaces.
53str.rstrip!
Remove trailing spaces from str and return nil if there are no changes.
54str.scan(pattern) [or]
Str.scan(pattern) { |match, ...| block }

The two forms match pattern (which can be a regular expression Regexp or a string String) traverse str. For each match, a result is generated and the result is added to the result array or passed to the block. If the pattern does not contain a grouping, each individual result consists of a matching string, $&. If pattern contains a grouping, each individual result is an array containing the entries for each grouping.
55str.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)

Remove the specified part from str and return the deleted part. If the value is out of range, the argument takes the form of Fixnum and an IndexError is generated. The argument is of the form range and will generate a RangeError with the arguments of Regexp and String , ignoring the execution of the action.
56str.split(pattern=$;, [limit])

Separating str into substrings based on delimiters And return an array of these substrings.

If pattern is a string String, it will be used as a separator when splitting str. If pattern is a single space, str is split based on spaces, ignoring leading and consecutive space characters.

If pattern is a regular expression Regexp, then str is split where the pattern matches. When pattern matches a string of length, str is split into a single character.

If the pattern parameter is omitted, the value of $; is used. If $; is nil (the default), str is split based on spaces, just like ` ` is specified as a separator.

If the limit parameter is omitted, the trailing null field is suppressed. If limit is a positive number, then the maximum number of fields is returned (if limit is 1, the entire string is returned as the only entry in the array). If limit is a negative number, the number of fields returned is not limited and the trailing null field is not suppressed.

57str.squeeze([other_str]*)
Use the program described for String#count to create a series of characters from the other_str parameter. Returns a new string in which the same characters that appear in the collection are replaced with a single character. If no arguments are given, all the same characters are replaced with a single character.
58str.squeeze!([other_str]*)
Same as squeeze, but str will change and return, if there is no change Return nil.
59str.strip
Returns a copy of str, removing leading spaces and trailing spaces.
60str.strip!
Remove leading and trailing spaces from str and return nil if there is no change.
61str.sub(pattern, replacement) [or]
Str.sub(pattern) { |match| block }

Returns a copy of str, and the first occurrence of pattern is replaced with the value of replacement or block. Pattern is usually a regular expression Regexp; if it is a string String, then no regular expression metacharacters are interpreted.
62str.sub!(pattern, replacement) [or]
Str.sub!(pattern) { |match| block }

Executes String#sub substitution and returns str, or nil if there is no replacement execution.
63str.succ [or] str.next
returns the inheritance of str.
64str.succ! [or] str.next!
is equivalent to String#succ, but str will change and return.
65str.sum(n=16)
returns the n-bit checksum of the characters in str, where n is optional The Fixnum parameter, which defaults 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.
66str.swapcase
Returns a copy of str, all uppercase letters are converted to lowercase letters, and all lowercase letters are converted to uppercase letters.
67str.swapcase!
is equivalent to String#swapcase, but str will change and return, or nil if there is no change.
68str.to_f
Returns the result of interpreting the leading character in str as a floating point number. Extra characters beyond the end of a valid number are ignored. Returns 0.0 if there is no significant digit at the beginning of str. This method does not generate an exception.
69str.to_i(base=10)
Returns the leading character in str as an integer base (base 2, 8, 10 or 16) results. Extra characters beyond the end of a valid number are ignored. Returns 0 if there is no valid number at the beginning of str. This method does not generate an exception.
70str.to_s [or] str.to_str
Returns the received value.
71str.tr(from_str, to_str)
Returns a copy of str, replacing the characters in from_str with the corresponding characters in to_str . If to_str is shorter than from_str, it will be filled with the last character. Both strings can use the c1.c2 symbol to represent the range of characters. If from_str begins with ^, it means all characters except the ones listed.
72str.tr!(from_str, to_str)
is equivalent to String#tr, but str will change and return if there is no change Then return nil.
73str.tr_s(from_str, to_str)
Process str according to the rules described by String#tr, then remove will affect translation Repeating characters.
74str.tr_s!(from_str, to_str)
is equivalent to String#tr_s, but str will change and return if there is no change Then return nil.
75str.unpack(format)
Decode str (possibly containing binary data) according to the format string, returning each value extracted Array. The format character consists of a series of single-character instructions. Each instruction can be followed by a number indicating the number of times the instruction is repeated. The asterisk (*) will use all remaining elements. The instruction sSiIlL may be followed by an underscore (_) after each, using the native size of the underlying platform for the specified type, otherwise a platform-independent size is used. Spaces in the format string are ignored.
76str.upcase
Returns a copy of str, and all lowercase letters are replaced with uppercase letters. The operation is environment insensitive and only the characters a through z are affected.
77str.upcase!
Change the contents of str to uppercase, or nil if there is no change.
78str.upto(other_str) { |s| block }
traverse continuous 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 directive

The following table lists the decompression instructions for the method String#unpack.

InstructionsReturnDescription
AString Remove trailing nulls and spaces.
aStringString.
BString Extracts the bits from each character (first the most significant bit).
bString Extract bits from each character (first the least significant bit).
CFixnum Extract a character as an unsigned integer.
cFixnum Extract a character as an integer.
D, dFloat treats characters of sizeof(double) as native doubles.
EFloat Treats characters of sizeof(double) length as doubles in littleendian byte order.
eFloat Treats characters of sizeof(float) length as floats of littleendian byte order.
F, fFloat treats characters of sizeof(float) as native floats.
GFloat treats characters of sizeof(double) as doubles in network byte order.
gFloat treats characters of sizeof(float) as a float in network byte order.
HString Extract hexadecimal from each character (first most significant bit).
hString Extract hexadecimal from each character (first least significant bit).
IInteger Treats consecutive characters of sizeof(int) length (modified by _) as native integers.
iInteger treats consecutive characters of sizeof(int) length (modified by _) as signed native integers.
LInteger treats four (via _ modified) consecutive characters as unsigned native long integers.
lInteger treats four (via _ modified) consecutive characters as signed native long integers.
MStringThe reference is printable.
mStringBase64 encoding.
NInteger treats four characters as an unsigned long in network byte order.
nFixnum treats two characters as unsigned shorts in network byte order.
PStringUses the character of sizeof(char *) as a pointer and returns the \emph{len} character from the referenced position.
pString Treats a character of sizeof(char *) as a pointer to a null end character.
QInteger treats eight characters as unsigned quad word (64 bits).
qInteger treats eight characters as signed quad word (64 bits).
SFixnum treats two consecutive characters (if different with _) as unsigned shorts in native byte order.
sFixnum treats two consecutive characters (if using _) as signed shorts in native byte order.
UIntegerUTF-8 characters as unsigned integers.
uStringUU encoding.
VFixnum treats four characters as unsigned long in little-endian byte order.
vFixnum treats two characters as unsigned shorts in little-endian byte order.
wIntegerBER Compressed integer.
X  Skip one character backwards.
x  Skip one character forward.
ZString is used with * to remove trailing null until the first null.
@ Skip the offset given by the length parameter.

Instance

Try the example below to extract the various data.

"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"]





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.