Andrew
Andrew

Reputation: 19

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

Upvotes: 1

Views: 288

Answers (2)

Stefan
Stefan

Reputation: 114178

When you enter "World", you are actually pressing 6 keys: World and enter (modifier keys like shift are not recognized as separate characters). The gets method therefore returns "World\n" with \n begin newline.

To remove such newlines, there's chomp:

"World\n".chomp
#=> "World"

Applied to your code: (along with some minor fixes)

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

Running the code gives:

=========================
Hello, World.
Enter the word you want to replace: World
Enter what you want the new word to be: Ruby
Hello, Ruby. 

Upvotes: 0

Nick Ellis
Nick Ellis

Reputation: 1077

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'

Upvotes: 1

Related Questions