# 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