14

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?

pang
  • 3,964
  • 8
  • 36
  • 42
  • 2
    A better title might be, "Case-insensitive string search & replace in Ruby". Changing the title to something like that might help you get more people looking at your question. – donut Nov 19 '09 at 09:40

4 Answers4

21

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.

hallski
  • 123,625
  • 4
  • 33
  • 21
3

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.

YOU
  • 120,166
  • 34
  • 186
  • 219
3

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
  • 51,832
  • 12
  • 88
  • 127
2

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."
Community
  • 1
  • 1
brianegge
  • 29,240
  • 13
  • 74
  • 99