Ruby redaction program logic?

700 views Asked by At

Okay, I am doing the codeacademy ruby track and I am not stock with the problem. I can make it works now, but I don't understand why it works. instructions for exercise:

Let's start simple: write an .each loop that goes through words and just prints out each word it finds.

I have broken the problem into steps to try to understand why it works but I am very confused. My code for the problem is:

puts "Text to search through: " #ask user for input
text = gets.chomp
#store the user's input into the variable text
puts "Text to be reducted: " 
#ask the user for input
redact = gets.chomp 
#store the user's input into the variable redact

words = text.split(" ") 
=begin
split the user's input into the variable words
store that input into the variable words
=end
words.each do |word| 
=begin
creates a placeholder for the user's input
then attach an expression to the input stored in
the variable words one at a time. The variable
words holds the value of the variable text
=end
    if word != redact 
=begin
if word (which now holds the value of words that's
stored in the variable text, and which is the user's input)
is not equal to the value of the variable redact do something
=end
        word = word + " "
=begin
increment the value of word by an empty space
why do I need to increment the value of word by an empty space? 
=end
        print "#{word}" #print the value of the variable word
else
    print "REDACTED" #otherwise, print the value redacted
end
end

The program works if I use a string separated by an space and only if I change

word = word + ""

instead of

word = word + " "

I would truly appreciate if someone break it down for me, step by step.

I created a video of it for a more visual explanation of it. here is the link: ruby redaction video

thank you.

2

There are 2 answers

0
Fred On

The problem in your video is that "nelson" is not the same as "nelson ", and the Codeacademy scoring doesn't see a match when you append a space to the word before printing it.

0
raaya1506 On

I am reading this problem in July 2019..

So anybody who is reading this problem and getting confused with the below part asked by the user:

word = word + " " =begin increment the value of word by an empty space why do I need to increment the value of word by an empty space?

So the answer is that the + sign is not for incrementing the value it's for adding a space and the + sign is used as string concatenator. So it has been placed there so that whatever words are being searched and displayed, they have a space between them.