Ruby Standard Type Summary _ruby topics

Source: Internet
Author: User
Tags abs delete key
First, the number
  1. Ruby supports integers and floating-point numbers, and integers can be arbitrary lengths
  2. 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
  3. 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
  4. 0xaabb # hex
  5. 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
  6. ? 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
  7. a numeric literal with a decimal point is converted to a float object
  8. All numbers are objects, no corresponding functions, but methods.
    Exp:
    The absolute value of the number is anumber.abs rather than ABS (Anumber)
  9. An integer useful iterator
  10. 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
Second, string
  1. Ruby's String is a 8-byte simple sequence, and the string is an object of the string class
  2. Note the conversion mechanism ( note the difference between single and double quotes), such as:
  3. 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
  4. Double quotes to support the escape of Polysemy
  5. "\ 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
  6. Here document to create a string that end_of_string as a closing symbol
  7. 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
  8. %q and%q separate strings into single and double quotation strings (that is, the%q and%q symbols have ', ' functions)
  9. %q/general single-quoted string/>> General single-quoted string
  10. String Common Features
  11. 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
Third, interval
    1. The interval exists in any place, such as: January-December. Ruby uses an interval to achieve 3 different characteristics: sequence, condition, interval.
    2. ".." : 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
    3. To_a converts the interval into a list
      Exp: (' bar ' ... ') Bat '). To_a >> ["Bar", "bas", "bat"]
    4. 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
    5. 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,
    6. Interval test
      Puts (1..10). Include? (3.14) => ture
      Puts (1..10) = = 3.14 => ture
Four, regular expressions
  1. 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
  2. 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
  3. Exp:
    A = "Fats Waller"
    A =~/a/>> 1
    A =~/z/>> nil
    A =~ "ll" >> 7
  4. Where the matching characters are returned, the other
  5. $& 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
  6. Pattern, any expression contains a pattern that matches the regular expression to the string
  7. 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
  8. \ followed by a letter or number that represents a specific structure such as the \s representation character.
  9. Anchor point A regular expression always returns the first match to find the pattern, how do you change it?
  10. 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



Five, character class
  1. The character class here is not an object-oriented class, only that these characters belong to a particular kind of
  2. 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
  3. Showre (' It costs $. ',/[aeiou]/) >> it c<<o>>sts.
  4. The sequence c1-c2 in square brackets indicates that all characters between the C1-C2 also include C1 and C2
  5. 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]
  6. 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.
  7. Character class abbreviation
  8. 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
  9. Repeat
  10. 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
  11. Replace
  12. "|" 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
  13. Group
  14. 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
  15. Pattern-based substitution
  16. 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"
  17. The backslash sequence is used in the substitution
  18. \& after the match
    Matching group after \+
    \ ' matches the preceding string
    \ ' matches the following string
    The literal value of the \ Backslash
  19. Object-oriented regular expressions
  20. 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 '
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.