删除另一个数组中存在的数组元素

Mik*_*dru 9 ruby arrays array-difference

有一个单词列表和禁止单词列表.我想通过单词列表并编辑所有被禁止的单词.这就是我最终做的事情(请注意catched布尔值):

puts "Give input text:"
text = gets.chomp
puts "Give redacted word:"
redacted = gets.chomp

words = text.split(" ")
redacted = redacted.split(" ")
catched = false

words.each do |word|
  redacted.each do |redacted_word|
    if word == redacted_word
        catched = true
        print "REDACTED "
        break
    end
  end
    if catched == true
        catched = false
    else
        print word + " "
    end
end
Run Code Online (Sandbox Code Playgroud)

有没有适当/有效的方法?

pan*_*ang 12

它也可以工作.

words - redacted
Run Code Online (Sandbox Code Playgroud)

+,-,&,这些方法是非常简单实用的.

irb(main):016:0> words = ["a", "b", "a", "c"]
=> ["a", "b", "a", "c"]
irb(main):017:0> redacted = ["a", "b"]
=> ["a", "b"]
irb(main):018:0> words - redacted
=> ["c"]
irb(main):019:0> words + redacted
=> ["a", "b", "a", "c", "a", "b"]
irb(main):020:0> words & redacted
=> ["a", "b"]
Run Code Online (Sandbox Code Playgroud)


pot*_*hin 7

您可以.reject用来排除redacted数组中存在的所有禁止的单词:

words.reject {|w| redacted.include? w}
Run Code Online (Sandbox Code Playgroud)

演示

如果要获取words阵列中存在的禁止词列表,可以使用.select:

words.select {|w| redacted.include? w}
Run Code Online (Sandbox Code Playgroud)

演示