Search code examples
arraysrubystringreplaceuser-input

Replacing a word in a string with user input [RUBY]


I'm trying to figure out how to replace a word in a string with a user string.

The user would be prompted to type which word they would like to replace, and then they would be again prompted to enter the new word.

For example the starting string would be "Hello, World." User would input "World" then they would input "Ruby" Finally, "Hello, Ruby." would print out.

So far Ive tried using gsub and the [] method neither worked. Any thoughts?

Here's my function so far:

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

Solution

  • The problem is gets also grabs the new line when a user inputs, so you want to strip that off. I made this silly test case in the console

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