Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can ruby do this task (Case-insensitive string search & replace in Ruby)?

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?

like image 361
pang Avatar asked Nov 19 '09 09:11

pang


3 Answers

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.

like image 76
hallski Avatar answered Oct 24 '22 23:10

hallski


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

like image 30
Mike Woodhouse Avatar answered Oct 25 '22 00:10

Mike Woodhouse


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."
like image 21
brianegge Avatar answered Oct 25 '22 00:10

brianegge