views:

222

answers:

4

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?

+2  A: 

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.

m5h
Updated example using the case insensitive flag to the regexp as was suggested by brianegge.
m5h
+1  A: 

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."
brianegge
I was writing the exact same thing.Here's the gsub documentation: http://ruby-doc.org/core/classes/String.html#M000817
Yoann Le Touche
+1  A: 

another version without brackets () in regex,

puts "What the human does is not like what animal does.".gsub(/what/i,'==\0==')

==What== the human does is not like ==what== animal does.

S.Mark
+1  A: 

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

Mike Woodhouse