From: Glen Pfeiffer Date: 2007-01-23T12:05:12+09:00 Subject: Re: Problems with replacing text --- Sam C. wrote: > I am creating a small chatbot program in Ruby, and I need it > to be able to change the word "I" to "You" when it is reading > the user input. this is the code I am using: > > uinput['I'] = 'you' You want to perform a "substitution" on the text contained in the variable. You can call the 'gsub!' method of the string object to perform a substitution. Here is an example from an irb session: irb(main):001:0> x = 'I love Perl' => "I love Perl" irb(main):002:0> x.gsub!('Perl', 'Ruby') => "I love Ruby" irb(main):003:0> puts x I love Perl The code only version is: x = 'I love Perl' x.gsub!('Perl', 'Ruby') puts x There are several other problems you may run into with this as well. For example, what are you going to do when the user enters a lowercase i? Or what if a word contains the letter i? I recommend using a regular expression. Regular Expressions: http://www.rubycentral.com/book/tut_stdtypes.html#S4 Pattern-Based Substitution http://www.rubycentral.com/book/tut_stdtypes.html#UK Here is another irb session: irb(main):004:0> x = 'I will eat pizza for dinner!' => "I will eat pizza for dinner!" irb(main):005:0> x.gsub!(/\bi\b/i, 'You') => "You will eat pizza for dinner!" irb(main):006:0> puts x You will eat pizza for dinner! => nil Again, the code only version: x = 'I will eat pizza for dinner!' x.gsub!(/\bi\b/i, 'You') puts x -- Glen