【发布时间】:2019-04-22 07:37:01
【问题描述】:
我试图弄清楚如何用用户字符串替换字符串中的单词。
系统会提示用户输入他们想要替换的单词,然后再次提示他们输入新单词。
例如,起始字符串是“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
【问题讨论】:
标签: arrays ruby string replace user-input