Redacted 6/6


#1

I'm trying to add multiple, separate words to redact as follows:

That case I have the following result:

What is my mistake?


#2

The problem is with the double print word statements. The word is printed in one or the other if statement so is printing twice when not redacted, and once when it is. The fix is to reduce the logic to one if statement:

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

#3

Great!
Also I still keep trying to find a solution how to save new redacted string as variable. Is it possible? Please advise for the method.


#4

We could construct an output string, but it may be better to construct an array then join the words at the end.

words=text.split(" ")
redacted = []
words.each do |word|
    if word != redact && word != redact2
        redacted << word
    else
        redacted << "REDACTED"
    end
end
print redacted.join(' ')

#5

Here is a multiword version that builds a string. This was written before it was explained that we should treat strings as immutable, ergo my statement in the above post.

# multiword redacter my mtf
def red(words,reds)
  rv = ""
  words.each do |word|
    if word != reds
      rv = rv + word + " "
    else
      rv = rv + "* "
    end
  end
  return rv
end
def apply(text,redact)
  r = redact.split(" ")
  r.each do |reds|
    words = text.split(" ")
    text = red(words,reds)
  end
  return text
end
print "Body text: "
text = gets.chomp
print "Redacted words: "
redact = gets.chomp
puts apply(text,redact)

Now that we know the practice is not recommended, we need to look at how to write an array, first, like in the earlier example.

def red(words,reds)
  rv = []
  words.each do |word|
    if word != reds
      rv << word
    else
      rv << "*" * word.length
    end
  end
  return rv.join(' ')
end

Test run

Body text:  a quick brown fox jumps over the lazy dog
Redacted words:  a brown the
* quick ***** fox jumps over *** lazy dog
nil

Note that the redacted word list is space separated, not comma separated.

To save the output in a variable, change this line,

puts apply(text,redact)

to

redacted_text = apply(text,redact)
puts redacted_text