# Ruby's gsub string substitution feature

Source: Internet
Author: User

# Ruby's gsub string substitution feature

1. You can use hash to replace the corresponding string:

"Hello 123 World". Gsub (/hello|world/, ' hello ' = ' hello ', ' world ' = ' world ') # = "Hello 123 World"

Although support for the second parameter is hash, but the symbol index is not supported, that is, hello: ' Hello ', World: ' World ' is invalid

"Hello 123 World". Gsub (/hello|world/, hello: ' Hello ', World: ' world ') # = "123"

Because no corresponding index was found, it was replaced with a null character.

2. You can replace a string with a regular expression:

"Hello 123 World". Gsub/(\d+)/, ' number ' # = "Hello number World"

3. You can use \1 \2 \ n ... To reference a matching substring

"Hello 123 World". Gsub/(\d+)/, "(\\1)" # = "Hello (123) World"

4. You can use block to process matching content

"Hello 123 World". Gsub/(\d+)/Do |m| M.to_i + 1end# = "Hello 124 World"

5. Multiple matching references in the block cannot be referenced by multiple block parameters, the following syntax is invalid:?

"His height is 175.00cm and weight 60.00kg.".    Gsub/(\d+\.\d+) (\w+)/do |height, unit| "%g%s"% [height, unit]end

Only the first parameter is fully matched to 175.00cm, and the following parameters are nil:height = 175.00cm, unit = Nil
The correct wording:
1.

"His height is 175.00cm and weight 60.00kg.".    Gsub/(\d+\.\d+) (\w+)/Do |matched| "%g%s"% [$, $2]end# = "His height is 175cm and weight 60kg."

2.

"His height is 175.00cm and weight 60.00kg.".    Gsub/(\d+\.\d+) (\w+)/Do |matched| "%g%s"% [regexp.last_match[1], regexp.last_match[2]]end# = "His height is 175cm and weight 60kg."


# Ruby's gsub string substitution feature

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.