- Ruby supports integers and floating-point numbers, and integers can be arbitrary lengths
- A range of integers are stored in binary, they belong to the Fixnum type, and are automatically converted to the Bignum type when the range is exceeded
- Expression: Symbol + A string of characters, the underline in the number string is ignored, (prefix includes: 0 for octal, 0x for hexadecimal, 0b for binary) 123_456_789_123_345_789 # Bignum
- 0xaabb # hex
- You can also get the integer value of the ASCII character and the value of the escape sequence by adding a question mark to the front
- ? A # Ordinary characters
? \ n # line feed (0x0a)
? \c-a # Ctrl + A (0X01)
? \m-a # Alt+a
? \m-\c-a # Ctrl+alt+a
? \c-? # Delete key
- a numeric literal with a decimal point is converted to a float object
- All numbers are objects, no corresponding functions, but methods.
Exp:
The absolute value of the number is anumber.abs rather than ABS (Anumber)
- An integer useful iterator
- 3.times {print "X"} => x x x 1.upto (5) {|i| Print I, ""} =>1 2 3 4 5 99.downto (km) {|i| Print I, "" "}=>99 50.step (5) {|i| Print I, ""}=>50
- Ruby's String is a 8-byte simple sequence, and the string is an object of the string class
- Note the conversion mechanism ( note the difference between single and double quotes), such as:
- The two consecutive backslashes in single quotes are replaced with a backslash, and a backslash is replaced with a single quote with a single quote
' Escape using ' \ ' >> escape to ' \ ' ' that\ ' s right ' >> ' s right
- Double quotes to support the escape of Polysemy
- "\ n"
#{expr} sequence to replace the value of any Ruby expression (Global, class, or instance variables, you can omit curly braces)
"Seconds/day: #{24*60*60}" >> seconds/day:86400 "#{' ho! ' *3}merry Christmas ">> ho! Ho! Ho! Merry Christmas ' This is line #$. ' >> This is line 3
- Here document to create a string that end_of_string as a closing symbol
- astring = << end_of_string The body of the ' STRING is the ' input lines up to one ending with the Same C5>text that followed the ' << ' end_of_string
- %q and%q separate strings into single and double quotation strings (that is, the%q and%q symbols have ', ' functions)
- %q/general single-quoted string/>> General single-quoted string
- String Common Features
- String#split: Breaking rows into fields
String#chomp: Remove line breaks
String#squeeze: Pruning characters that are repeatedly entered
String#scan: Specifies the pattern that you want the block to match
Exp:
/jazz/j00132.mp3 | 3:45 | Fats Waller | Ain ' t Misbehavin '
/jazz/j00319.mp3 | 2:58 | Louis Armstrong | Wonderful World
#文件格式如上, to decompose
Songs = Songlist.new
Songfile.each do |line|
file, length, name, title = Line.chomp.split (/\s*\|\s*/) #先chomp, then decompose,/\s* represents any character
name.squeeze! ("") #替换空格
mins, secs = Length.scan (/\d+/) #这里用scan匹配模式
Songs.append song.new (title, name, Mins.to_i*60+secs.to_i)
End
- The interval exists in any place, such as: January-December. Ruby uses an interval to achieve 3 different characteristics: sequence, condition, interval.
- ".." : Two dots to create a closed range, "...": and three dot to create a right open range (that is, the right edge does not take a value)
exp:0.. Anarray.length-1 equal to 0...anarray.length
- To_a converts the interval into a list
Exp: (' bar ' ... ') Bat '). To_a >> ["Bar", "bas", "bat"]
- The total usage of the interval
digits = 0..9
Digits.include? (5) >> True
Digits.min >> 0
Digits.max >> 9
Digits.reject {|i| i < 5} >> [5, 6, 7, 8, 9]
Digits.each do |digit|
Dial (Digit)
End
- Ruby can use the interval of its defined object to require that the object must be able to respond to the SUCC method to return the next object in the sequence, and that the object must be able to be compared using the <=> operator, the conventional comparison operator,
- Interval test
Puts (1..10). Include? (3.14) => ture
Puts (1..10) = = 3.14 => ture
Four, regular expressions
- A regular expression is an object of type RegExp, you can use the constructor to explicitly create a regular expression, or you can use the literal form/pattern/and%r\pattern\ to create
- Matches the string using the form of Regxp#match (astring) or the matching operator =~ (positive match) and!~ (negative match). Matching operators are defined in string and regexp, and if two operands are strings, the right-hand one is converted to a regular expression
- Exp:
A = "Fats Waller"
A =~/a/>> 1
A =~/z/>> nil
A =~ "ll" >> 7
- Where the matching characters are returned, the other
- $& accept the string part that is matched by the pattern
$ ' Accept the string part before the match
$ ' Accept the string after.
Exp: The following methods will be used in subsequent
def showre (A,re)
If a =~ re
"#{$ '}<<#{$&}>>#{$ '}" #返回前, middle, and post
Else
"No Match"
End
End
- Pattern, any expression contains a pattern that matches the regular expression to the string
- mode except., |, (,), [, {, +, \, ^, $, *, and? Other than a word that matches its own
If you want to match these special characters, you need to prefix them with a backslash, and analyze the above examples.
/\s*\|\s*/, the prefix was added/prefixed before \s and |
Showre (' kangaroo ',/angar/) >> K<<angar>>oo
Showre ('!@%&-_=+ ',/%&/) >> !@<<%&>>-_=+
Showre (' yes | no ',/\|/) >> Yes <<|>> no
- \ followed by a letter or number that represents a specific structure such as the \s representation character.
- Anchor point A regular expression always returns the first match to find the pattern, how do you change it?
- Patterns ^ and $ are used to match the beginning and end of the line, respectively
The sequence \a the position where the string starts, \z and \z match the end of the string.
\b and \b Match word boundary and non word boundary respectively
Showre ("This is\nthe time",/^the/) >> this is\n<<the>> time
Showre ("This is\nthe time",/is$/) >> this <<is>>\nthe time
Showre ("This is\nthe time",/\athis/) >> <<this>> is\nthe Time
- The character class here is not an object-oriented class, only that these characters belong to a particular kind of
- A character class is a collection of characters that are expanded with square brackets: [characters] matches all the single characters in the square brackets. [Aeiou] matches the vowel, [,.: '!?] Matching punctuation and so on
- Showre (' It costs $. ',/[aeiou]/) >> it c<<o>>sts.
- The sequence c1-c2 in square brackets indicates that all characters between the C1-C2 also include C1 and C2
- A = ' Gamma [design patterns-page 123] '
Showre (A,/[]]/) >> Gamma [design patterns-page 123<<]>>
Showre (A,/[b-f]/) >> Gamma [<<d>>esign patterns-page 123]
Showre (A,/[-]/) >> Gamma [design patterns<<->>page 123]
Showre (A,/[0-9]/) >> Gamma [design patterns-page <<1>>23]
- followed by the opening parenthesis ([) is the character ^, which represents the negation of this character class: [^a-z] matches any character that is not a lowercase letter.
- Character class abbreviation
- Sequence as [...] meaning
\d [0-9] Digit character
\d [^0-9] Nondigit
\s [\s\t\r\n\f] whitespace character matches a single blank character
\s [^\s\t\r\n\f] nonwhitespace character
\w [a-za-z0-9_] Word character
\w [^a-za-z0-9_] Nonword character
- Repeat
- R * matches the presence of 0 or more R
R + matches the presence of one or more R
R? Match the presence of 0 or 1 R
R {M,n} matches the presence of at least m up to n R
R {m,} matches the presence of at least M R
Duplicate structures have high precedence: they are bundled only with the direct regular expression precursors in the pattern
/ab+/matches a "a" followed by a live multiple "B" instead of "AB" sequences
/a*/matches any string: 0 or more "a" of any string.
Exp:
A = "The moon is made of cheese"
Showre (A,/\w+/) >> <<The>> Moon is made of cheese
Showre (A,/\s.*\s/) >> the<< Moon is made of >>cheese
Showre (A,/\s.*?\s/) >> the<< Moon >>is made of cheese
Showre (A,/[aeiou]{2,99}/) >> The m<<oo>>n is made of cheese
Showre (A,/mo?o/) >> The <<moo>>n is made of cheese
- Replace
- "|" Match both the regular expression in front of it or the following
A = "red ball Blue Sky"
Showre (A,/d|e/) >> r<<e>>d ball Blue Sky
Showre (A,/al|lu/) >> red B<<al>>l Blue Sky
Showre (A,/red ball|angry sky/) >> <<red ball>> Blue Sky
- Group
- Parentheses group regular expressions, and the contents of the group are treated as a single regular expression
Showre (' banana ',/(AN) +/) >> B<<anan>>a
# match the repeated letters
Showre (' He said ' Hello ',/(\w) \1/) >> He said "He<<ll>>o"
# matches a duplicate substring
Showre (' Mississippi ',/(\w+) \1/) >> M<<ississ>>ippi
- Pattern-based substitution
- Have you ever thought about, case replacement.
Methods String#sub and String#gsub both search the string for the part that matches the first parameter, and then replace them with the second argument. String#sub is replaced only once, and String#gsub replaces all matches found. Returns a copy of the new string that contains the replacement. The evolutionary version is string#sub! and string#gsub!.
A = "The quick brown fox"
A.sub (/[aeiou]/, ' * ') >> "th* quick brown Fox"
A.gsub (/[aeiou]/, ' * ') >> "th* q**ck br*wn f*x"
A.sub (/\s\s+/, ') >> "The brown Fox"
A.gsub (/\s\s+/, "") >> "the"
The second argument can be a block of code
A = "The quick brown fox"
A.sub (/^./) {$&.upcase} >> "The Quick brown fox"
A.gsub (/[aeiou]/) {$&.upcase} >> "The QUIck brOwn fOx"
- The backslash sequence is used in the substitution
- \& after the match
Matching group after \+
\ ' matches the preceding string
\ ' matches the following string
The literal value of the \ Backslash
- Object-oriented regular expressions
- The literal value of the regular expression creates the RegExp class
Re =/cat/
Re.type >> Regexp
Method Regexp#match matches a regular expression from a string, if unsuccessful, the method returns nil and, if successful, returns an instance of the Matchdata class
Exp:
E =/(\d+):(\d+)/# Match a time hh:mm
MD = Re.match ("time:12:34am")
Md.type >> Matchdata
Md[0] # = = $& >> "12:34"
MD[1] # = = $ >> "12"
MD[2] # = = $ >> "34"
Md.pre_match # = = $ ' >> ' time: '
Md.post_match # = = $ ' >> ' AM '