Home > Back-end >  Each method in Ruby not working as I expected
Each method in Ruby not working as I expected

Time:01-15

I have two inputs and I am trying to print the first one but if any of those elements on the second array is the same than any of the elements of the second array it should print the word "REDACTED" instead of that element. But I'm not having the expected result

input 1 a b c d input 2 a c

expected result REDACTED b REDACTED d but my result is this REDACTED b REDACTED c c d d

puts "Enter some text: "
text = gets.chomp

puts "Enter words to redact: "
redact = gets.chomp

words_text = text.split(" ")
words_redact = redact.split(" ")

words_text.each do |word|
  words_redact.each do |r_word|
    if word == r_word
      print "REDACTED "
      break
    else
      print word   " "
    end
  end
end

CodePudding user response:

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

CodePudding user response:

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
  •  Tags:  
  • Related