我正试图找出如何用用户字符串替换字符串中的单词。
系统将提示用户键入要替换的单词,然后再次提示用户输入新单词。
例如,起始字符串为"Hello,World"用户将输入"世界"然后他们会输入"Ruby"最后,"你好,鲁比"就会打印出来。
到目前为止,我尝试过使用gsub,[]方法都不起作用。有什么想法吗?
到目前为止,我的功能是:
def subString(string)
sentence = string
print"=========================n"
print sentence
print "n"
print "Enter the word you want to replace: "
replaceWord = gets
print "Enter what you want the new word to be: "
newWord = gets
sentence[replaceWord] = [newWord]
print sentence
#newString = sentence.gsub(replaceWord, newWord)
#newString = sentence.gsub("World", "Ruby")
#print newString
end
问题是,当用户输入时,gets也会抓取新行,所以你想去掉它。我在控制台中做了这个愚蠢的测试用例
sentence = "hello world"
replace_with = gets # put in hello
replace_with.strip!
sentence.gsub!(replace_with, 'butt')
puts sentence # prints 'butt world'
当您进入"世界"时,您实际上按下了6个键:Wo1123>和5nter的修饰符键不会被识别为单独的字符(。因此,gets
方法返回"Worldn"
,其中n
开始换行。
要删除这些换行符,有chomp
:
"Worldn".chomp
#=> "World"
应用于您的代码:(以及一些小的修复(
sentence = "Hello, World."
puts "========================="
puts sentence
print "Enter the word you want to replace: "
replace_word = gets.chomp
print "Enter what you want the new word to be: "
new_word = gets.chomp
sentence[replace_word] = new_word
puts sentence
运行代码给出:
=========================
Hello, World.
Enter the word you want to replace: World
Enter what you want the new word to be: Ruby
Hello, Ruby.