5/6: Why isn't redact word isn't getting replaced?


#1

I'm on lesson 5/6: Control Flow Know How. And when I execute my code, it doesn't replace the word I want to redact.

Here's my code:

puts "Welcome to the redactor! Simply enter the text you want to search through:"
text = gets.chomp
puts "Now enter the name or word you would like to redact:"
redact = gets.chomp

words = text.split(" ")

words.each do |word|
    print word
    if word == redact
        print "REDACTED"
    else
        print word + " "
    end
end

My text was "My name is Frogman", and my redact word was "Frogman", which printed to the console:

"MyMy namename isis FrogmanREDACTED"

I edited my code a little to fix that the repeating words, by printing a space instead of word + " ".

So now my code looks like this:

puts "Welcome to the redactor! Simply enter the text you want to search through:"
text = gets.chomp
puts "Now enter the name or word you would like to redact:"
redact = gets.chomp

words = text.split(" ")

words.each do |word|
    print word
    if word == redact
        print "REDACTED "
    else
        print " "
    end
end

And it prints to the console "My name is FrogmanREDACTED", it doesn't actually replace "Frogman" with "REDACTED", it just printed "REDACTED" afterwards. How can I fix that?

Thanks in advance!


#2

Never mind, I just realized What I did wrong, in my loop I was printing word(first line in the loop), which kept repeating it. By the way, how do you delete a topic? I couldn't figure out how to delete this one.