Exotic variables in ruby

Source: Internet
Author: User
Ruby used to learn a lot from perl, one of which is the global magic variable. Among these variables, it is estimated that no $ _ is more strange. For example, the gets method has this effect: while returning the row data you just read, it also saves the row data to $ _. if you call the print method without parameters, it prints the content in $. If you use only one regular expression as a condition when writing an if or while statement, the regular expression automatically matches $ _. in this case, we can write the following short and concise program to find the rows containing the email address in all the rows. 1 while gets
2 if/[a-zA-Z0-9 \. \-_] @ [a-zA-Z0-9 \. \-_]/
3 print
4 end
5end
6

However, this is not concise for Ruby. We can use ARGF. each {| line | print line if line = ~ /[A-zA-Z0-9 \. \-_] @ [a-zA-Z0-9 \. \-_]/}

Haha, what's the matter? I'm surprised. A statement is done, and ruby is efficient!

There is also a global variable, $. which contains the total number of lines of the file.

Other global variables $ &, & ', &' are used in regular expressions.

When you use match or = ~ When matching a string and a regular expression, the result is: $ & stores the part of the string that matches the regular expression, $ 'stores the previous string in the $ & part of the string, $ 'stores the last string of $ & in the string.

For example

Str = "good day! Woodfish1988@163.com It's a email"
Reg =/[a-zA-Z0-9 \-\. _] + @ [a-zA-Z0-9 \-\. _] +/
Reg = ~ Str
Puts $ ', $ &, $'

 

The result is

Good day!
Woodfish1988@163.com
It's a email

At the same time, the global scalar $1 after matching .. $9 contains small content that matches the regular expression (that is, the content enclosed by brackets). For details, see the regular expression tutorial)

For example:

Code = "<a href = 'HTTP: // www.google.com '> Google </a>"
Reg =/<a href = '(. +)'> (. +) <\/a>/
Reg = ~ Code
Puts $1, $2

 

The result is

Http://www.google.com
Google

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.