Reputation: 59
print "Enter your text here:"
user_text = gets.chomp
user_text_2 = user_text.gsub! "Damn", "Darn"
user_text_3 = user_text.gsub! "Shit", "Crap"
puts "Here is your edited text: #{user_text}"
I would like that code to also recognize when I use the lowercase versions of Shit and Damn and replace them with the substitute words. Right now it only recognizes when I type the words in with an uppercase first word. Is there any way to get it to recognize the lowercase words too, without adding more gsub! lines of code?
Upvotes: 0
Views: 207
Reputation: 1840
Just a very short solution:
user_text.gsub!(/[Dd]amn/, 'Darn')
The more general approach, if this is what you want, is with an i which makes the regex case-insensitive.
user_text.gsub!(/damn/i, 'Darn')
Upvotes: 1
Reputation: 6404
Use regular expressions instead of strings. So /damn/i
instead of "damn".
The 'i' at the end of a regular expression means ignore casing.
Upvotes: 0
Reputation: 106912
You can do that with a Regexp and the i
option, that makes the Regexp case insensitive:
foo = 'foo Foo'
foo.gsub(/foo/, 'bar')
#=> "bar Foo"
foo.gsub(/foo/i, 'bar') # with i
#=> "bar bar"
Upvotes: 0
Reputation: 61510
You can specify the i
flag on your patten to ignore case:
user_text_2 = user_text.gsub! /Damn/i, "Darn"
Upvotes: 3