2

I have the samples lines, and I want to substitute the leading #s with =s. (The first two lines) But instring.gsub!(/^#+\w/, ""), I can not get the number of # which I want to substitute.

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

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

The expected result:

==Command-line Tool
===Installment
This is a '#'.
2
  • So do you want to replace all the # in your string or only specific occurances? IF you want to replace all the # present, then you could simple do myString.gsub("#", "=") Commented Dec 12, 2011 at 11:35
  • Not really, only the leading one, and as the leading one varies from one to the other, I need to count them in the substitution. Commented Dec 12, 2011 at 11:48

1 Answer 1

11

a callback block function to the gsub method, probably. I am not sure what you had in mind but could be something like

s.gsub(/^(#+)\w+/) {|m| m.gsub("#", "=") }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, one question. does m means the one match? ?
the block argument is the match yes, but in the block, if you want, you can access the perl-ish match variables ($1, $` etc). More infos at ruby-doc.org/core-1.9.3/String.html#method-i-gsub

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.