首页 > 解决方案 > 用用户输入替换字符串中的单词 [RUBY]

问题描述

我试图弄清楚如何用用户字符串替换字符串中的单词。

将提示用户键入他们想要替换的单词,然后再次提示他们输入新单词。

例如,起始字符串是“Hello, World”。用户输入“World”,然后输入“Ruby”,最后输入“Hello, 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

标签: arraysrubystringreplaceuser-input

解决方案


问题是当用户输入时也会抓住新行,所以你想把它去掉。我在控制台中做了这个愚蠢的测试用例

sentence = "hello world"
replace_with = gets  # put in hello
replace_with.strip!
sentence.gsub!(replace_with, 'butt')
puts sentence  # prints 'butt world'

推荐阅读