How to use ruby ​​regexp to replace a string with a callback function, such as manipulation

I have sample strings and want to replace the lead #with =s. (First two lines) But in string.gsub!(/^#+\w/, "")I cannot get the number #I want to replace.

In javascript, I could use the callback function using the method replace, but how can I archive this Ruby?

##Command-line Tool
###Installment
This is a '#'.

Expected Result:

==Command-line Tool
===Installment
This is a '#'.
+1
source share
1 answer

callback block function for gsub method, probably. I'm not sure what you meant, but maybe something like

s.gsub(/^(#+)\w+/) {|m| m.gsub("#", "=") }
+9
source

Source: https://habr.com/ru/post/1625473/


All Articles