Each method in Ruby not working as I expected
The problem is with 2 each, you have 2 loops and if for each occurence you print at least print word + " "
.
A better approch would be to use include? and loop through a single array.
result = words_text.map do |word|
if words_redact.include? word
"REDACTED"
else
word
end
end
print result
Others are quite correct that using #include?
is the best way to address this, but you can iterate over the redacted words array to check each word. We set a flag called should_be_redacted
to false
, then iterate over words_redact
. If any of those words equals the word we're looking for, we change should_be_redacted
to true
, and break
to avoid doing unnecessary work.
Then we simply need to decide what to print based on the value of should_be_redacted
.
words_text.each do |word|
should_be_redacted = false
words_redact.each do |r_word|
if word == r_word
should_be_redacted = true
break
end
end
print "#{should_be_redacted ? 'REDACTED' : word} "
end
You may wish to compare in a case-insentive way.
words_text.each do |word|
should_be_redacted = false
words_redact.each do |r_word|
if word.upcase == r_word.upcase
should_be_redacted = true
break
end
end
print "#{should_be_redacted ? 'REDACTED' : word} "
end
We can simplify using the #any?
method to handle the short-circuiting for us and the boolean value.
words_text.each do |word|
should_be_redacted =
words_redact.any? do |r_word|
word.upcase == r_word.upcase
end
print "#{should_be_redacted ? 'REDACTED' : word} "
end