Ruby standard type Summary

Source: Internet
Author: User
Tags character classes

I. Numbers

  1. Ruby supports integers and floating-point numbers. integers can be of any length.
  2. Integers within a certain range are stored in binary. They belong to the fixnum type. If they exceed this range, they are automatically converted to the bignum type.
  3. Expression: Symbol + a string of characters,The underline in the number string is ignored,(Prefix: 0 indicates octal, 0x indicates hexadecimal, and 0b indicates binary.) 123_456_789_123_345_789 # Bignum
    0 xaabb # hexadecimal
  4. You can also add a question mark to get the integer corresponding to the ASCII character and the value of the escape sequence.
    ? A # common characters
    ? \ N # linefeed (0x0a)
    ? \ C-a # CTRL + a (0x01)
    ? \ M-a # ALT +
    ? \ M-\ C-a # CTRL + ALT +
    ? \ C -? # Delete key
  5. A numeric literal with a decimal point is converted to a Float object.
  6. All numbers are objects and there is no corresponding function but a method.
    Exp:
    The absolute value of a number is aNumber. abs instead of abs (aNumber)
  7. Integer useful iterator
    3. times {print "X" }=> X1. upto (5) {| I | print I, "" }=> 1 2 3 4 599. downto (95) {| I | print I, "" }=> 99 98 97 96 95 50. step (80, 5) {| I | print I, "" }=> 50 55 60 65 70 75 80
Ii. String
  1. The Ruby String is a simple 8-byte sequence, and the String is a String object.
  2. Note the conversion mechanism (Note the difference between single quotes and double quotes), Such:
    The two backslashes connected to each other in single quotes are replaced with a backslashes. A backslashes followed by a single quotation mark are replaced with a single quotation mark.
    'Escape using "\" '> escape "\"'That \'s right'> That's right
  3. Double quotation marks support multi-meaning escape
    "\ N"
    # {Expr} sequence to replace the value of any Ruby expression,(Braces can be omitted for global variables, class variables, or instance variables)
    "Seconds/day: # {24*60*60}"> Seconds/day: 86400"# {'Ho! '* 3} Merry Christmas "> Ho! Ho! Ho! Merry Christmas"This is line # $."> This is line 3
  4. Here document to create a string, end_of_string is the end symbol
    AString = <END_OF_STRING The body of the string Is the input lines up One ending with the sameText that followed the '<' END_OF_STRING
  5. % Q and % Q separate the strings into single quotes and double quotation marks respectively (I .e., the symbols after % q and % Q have the ', "function)
    % Q/general single-quoted string/> general single-quoted string
  6. Common functions of String
    String # split: splits rows into fields.
    String # chomp: Remove line breaks
    String # squeeze: removes the characters that have been repeatedly entered.
    String # scan: Specify the pattern for block matching
    Exp:
    /Jazz/j00132.mp3 | Fats Waller | Ain't Misbehavin'
    /Jazz/j00319133 | Louis Armstrong | Wonderful World
    # The file format is as follows:
    Songs = SongList. new
    SongFile. each do | line |
    File, length, name, title = line. chomp. split (/\ s * \ | \ s */) # chomp first, then decomposed, And/\ s * indicates any character
    Name. squeeze! ("") # Replace Spaces
    Mins, secs = length. scan (/\ d +/) # scan matching mode is used here
    Songs. append Song. new (title, name, mins. to_ I * 60 + secs. to_ I)
    End
III, Interval
  1. The interval exists anywhere, for example, from 1 to December. Ruby uses intervals to implement three different features: sequence, condition, and interval.
  2. "...": Create a closed interval for the two dots, "...": create a right-open interval for the three dots (that is, the right boundary is not valid)
    Exp: 0... anArray. length-1 is equivalent to 0... anArray. length
  3. To_a converts an interval to a list.
    Exp: ('bar'... 'bat '). to_a> ["bar", "bas", "bat"]
  4. Common interval usage
    Digits = 0 .. 9
    Digits. include? (5)> true
    Digits. min> 0
    Digits. max> 9
    Digits. reject {| I <5}> [5, 6, 7, 8, 9]
    Digits. each do | digit |
    Dial (digit)
    End
  5. Ruby can return the interval of an object defined by itself. This object must be able to respond to the succ method to return the next object in the sequence, and this object must be able to be compared using the <=> operator, that is, regular comparison operators,
  6. Interval Test
    Puts (1 .. 10). include? (3.14) => ture
    Puts (1 .. 10) === 3.14 => ture
Iv. Regular Expressions
  1. The regular expression is a Regexp-type object. You can use the constructor to explicitly create a regular expression, or use the literal value form/pattern/and % r \ pattern \ to create a regular expression.
  2. Regxp # match (aString) format or matching operator = ~ (Positive match) and !~ (Negative match) to match the string. The matching operator is defined in both String and Regexp. If both operands are strings, the one on the right will be converted to a regular expression.
    Exp:
    A = "Fats Waller"
    A = ~ /A/> 1
    A = ~ /Z/> nil
    A = ~ "Ll"> 7
  3. The above returns the position of the matching character.
    $ & Accept the string part matched by the pattern
    $ 'Accept the string part before matching
    $ 'Accept the string.
    Exp: The following methods will be used later.
    Def showRE (a, re)
    If a = ~ Re
    "#{$ '}<#{$ & }>#{$'}" # Returns the front, center, and back
    Else
    "No match"
    End
    End
  4. Mode. Any expression contains a pattern used to match a regular expression with any string.
    In the mode, except for., |, (,), [, {, +, \, ^, $, *, and? All other words match themselves.
    If you want to match these special characters, you need to add the backslash as the prefix to analyze the above example.
    /\ S * \ | \ s */. prefix/is added before \ s and |.
    ShowRE ('hangaroo ',/angar/)> k <angar> oo
    ShowRE ('! @ % &-_ = + ',/% &/)>! @ <% &>-_ = +
    ShowRE ('yes | no', // |/)> yes <|> no
  5. \ Is followed by a letter or number indicating a specific structure, such as \ s.
  6. A regular expression of the anchor always returns the first matching of the pattern. How can this change?
    Modes ^ and $ are used to match the beginning and end of a row.
    Sequence \ A matches the start position of the string, and \ z and \ Z match the end position of the string
    \ B and \ B match the 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

V. character classes

  1. The character class here is not an object-oriented class. It only indicates that these characters belong to a special type.
  2. A character class is a set of characters expanded with square brackets: [characters] matches all single characters in square brackets. [Aeiou] matches the vowel, [,.: '!?] Match punctuation marks, etc.
    ShowRE ('It costs $12. ',/[aeiou]/)> It c <o> sts $12.
  3. The sequence c1-c2 in square brackets represents all characters between the c1-c2 that also contain 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]
  4. The character ^ is followed by the opening brackets ([), which indicates the negation of this character class: [^ a-z] matches any character that is not a lowercase letter.
  5. Abbreviations
    The sequence is shown in [...] 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
  6. Repeated
    R * matches 0 or multiple r records.
    The appearance of r + matching one or more r
    R? Occurrence of matching 0 or 1 r
    The appearance of r {m, n} matching at least m up to n r
    The appearance of r {m,} matching at least m r

    The repeat structure has a high priority: that is, they are only bundled with the forward Regular Expression in the pattern.
    /AB +/match a "a" followed by a "B", not a "AB" sequence.
    /A */will match any string: 0 or multiple "a" strings.
    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
  7. Replace
    "|" Matches the regular expression or
    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
  8. Group
    Parentheses group regular expressions. The content in the group is treated as a separate regular expression.
    ShowRE ('banana ',/(an) +/)> B <anan>
    # Matching duplicate letters
    ShowRE ('he said "Hello" ',/(\ w) \ 1/)> He said "He <ll> o"
    # Matching repeated substrings
    ShowRE ('Mississippi ',/(\ w +) \ 1/)> M <ississ> ippi
  9. Mode-based replacement
    Have you ever thought about replacing the case with the upper or lower case.
    Methods String # sub and String # gsub search for the part matching the first parameter in the String, and then replace them with the second parameter. String # sub is replaced only once, while String # gsub replaces all matched items. 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 second parameter can be a code block.
    A = "the quick brown fox"
    A. sub (/^./) {$ &. upcase}> "The quick brown fox"
    A. gsub (/[aeiou]/) {$ &. upcase}> "thE qUIck brOwn fOx"
  10. The backslash sequence is used in replacement.
    \ & Matching
    \ + Matched group
    \ 'Match the preceding string
    \ 'Matches the string
    \ Backslash Literal Value
  11. Object-oriented Regular Expressions
    Create Regexp class for the literal value of a regular expression
    Re =/cat/
    Re. type> Regexp
    Method Regexp # match matches a regular expression from the string. If it fails, the method returns nil. If it succeeds, an instance of the MatchData class is returned.
    Exp:
    E =/(\ d +) :( \ d +)/# match a time hh: mm
    Md = re. match ("Time: 12: 34 am ")
    Md. type> MatchData
    Md [0] #== &>"
    Md [1] #==$ 1> "12"
    Md [2] #==$ 2> "34"
    Md. pre_match #== '> "Time :"
    Md. post_match #== '> "am"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.