Rather than arbitrarily seek a fixed number of redacted terms, create an array of terms and write a method that takes that array as a parameter. Then it can be one, two, or more terms passed as a single object to the function.
def redacted(text, words)
text = text.split(' ')
words.each do |word|
text.each do |term|
if term == word
text[text.find_index(term)] = "REDACTED"
print redacted("the rain in Spain falls mainly in the plains", ['the', 'in'])
["REDACTED", "rain", "REDACTED", "Spain", "falls", "mainly", "REDACTED", "REDACTED", "plains"]
puts redacted("the rain in Spain falls mainly in the plains", ['the', 'in']).join(' ')
REDACTED rain REDACTED Spain falls mainly REDACTED REDACTED plains
Redact a list
We don’t have to use a function, but it is more re-usable. In a one-off situation, the code inside the function can be applied inline. For the two-word example above, simply write the two inputs to an array that can be used by the code. There is no need for
|| (boolean) or
or (control flow) operations.
One should be mindful of the differences between
||. For our purposes at this stage of learning, the boolean is the one to reach for. The two are not synonymous.
Using “and” and “or” in Ruby