this is my code
i don’t know why it doesn’t work
puts"word to search through"
text=gets.chomp
puts"word to redact"
redact=gets.chomp
word= text.split(" ")
word.each { |word|print word}
if
redact==word
print “REDACTED "
else
print word +” "
end
you should put if else statement inside the each {}
puts"word to search through"
text=gets.chomp
puts"word to redact"
redact=gets.chomp
word= text.split(" ")
word.each { |word|
if
word == redact
print “REDACTED "
else
print word +” "
end
}
I got the answer but I didn’t understand the codes. Can you please explain how is the output in the console working after .each statement.
In the each
statement, we’re defining a variable with |word|
which will represent the current element of the array we’re working on (because the split
method returns an array).
Then we use an if/else statement to print REDACTED if the current element is equal to the word we’re looking for (redact
). If it’s not the correct word, we just print it normally. We also add the space.
Note that using word
as a variable even though our array is also called word
is a bit problematic for reading purposes (it doesn’t seem to cause a problem for Ruby because I assume the array called word is outside of the scope of the block (the {}
), but I’m no expert). A better alternative would be to choose something different from the name of the array, like a simple w
for example.
Hi I am sorry to response you late .I think arjofocolovi explain to you well