I have some problem with replace string in Ruby.
My Original string : What the human does is not like what animal does.
I want to replace to: ==What== the human does is not like ==what== animal does.
I face the problem of case sensitive when using gsub. (eg. What , what) I want to keep original text.
any solution?
If I understood you correctly this is what you want to do:
puts "What the human does is not like what animal does.".gsub(/(what)/i, '==\1==')
which will output
==What== the human does is not like ==what== animal does.
The important thing to take account of in all 3 answers so far, is the use of the "i" modifier on the regular expression. This is the shorthand way to specify the use of the Regexp::IGNORECASE
option.
A useful Ruby Regexp tutorial is here and the class is documented here
Use the block form of gsub.
"What the human does is not like what animal does.".gsub(/(what)/i) { |s| "==#{s}==" }
=> "==What== the human does is not like ==what== animal does."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With