【问题标题】:Replacing a word in a string with user input [RUBY]用用户输入替换字符串中的单词 [RUBY]
【发布时间】: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


    【解决方案1】:

    当你进入“世界”时,你实际上是按了6个键:World 和 enter (修饰键如 shift 不会被识别为单独的字符)。 gets 方法因此返回 "World\n"\n begin newline

    要删除这样的换行符,有chomp:

    "World\n".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. 
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-08
        • 2017-09-07
        • 1970-01-01
        • 1970-01-01
        • 2015-07-03
        相关资源
        最近更新 更多