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 quotes 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 a range 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 next object in the sequence based on the defined object range. This object must be able to respond to the succ method, in addition, this object must be able to be compared using the <=> operator, that is, the conventional comparison operator.
    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 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 appear
    r + matches one or more R appear
    r? Occurrence of matching 0 or 1 r
    r {m, n} matching at least m up to n r
    r {M ,} the occurrence of matching at least M r

    duplicate structure has a high priority: that is, they are only bundled with the forward Regular Expression in the pattern
    /AB +/matches a "A" followed by a living multiple "B ", instead of the "AB" sequence
    /A */will match any string: 0 or multiple "A" strings.
    Exp:
    A = "the moon is made of cheese"
    showre (, /\ W +/) >>< moon is made of cheese
    showre (A,/\ s. * \ s/)> the cheese
    showre (A,/\ s. *? \ S/)> the is made of cheese
    showre (A,/[aeiou] {2, 99}/)> the m N is made of cheese
    showre (A,/Mo? O/)> the 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 wondered whether to use case-based replacement.
    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"
    . sub (/[aeiou]/, '*')> "th * quick brown fox"
    . gsub (/[aeiou]/, '*')> "th * q ** CK Br * wn f * X"
    . sub (/\ s +/, '')>" the brown fox "
    . gsub (/\ s +/, '')>" the "
    the second parameter can be a Code block
    A =" The quick brown fox "
    . sub (/^. /) {$ &. upcase >>> "The quick brown fox"
    . 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.