如何消除具有一定价值的数组项

时间:2014-04-08 02:49:28

标签: ruby

我有一个arr3 = ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]item = ["dD"]的数组。我想要消除那些有" dD"或者" Dd"。

我想要的结果是[" Ac,Ab,Aa"," Ba,Bb,Bd"," Ca,Cc,Cb",&#34 ; aA,aC,aD"," bD,bA,bB"," cB,cA,cC"]。

我尝试了以下操作,但它没有用,它没有过滤掉任何项目,因此arr3保持不变:

arr3 = ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc",
        "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"] 
item = ["dD"]

def eliminate (from, item) 
  item1 =  item.join
  item2 = item1.reverse
  from.select { |pair| !pair.include? item1 or !pair.include? item2} 
end

eliminate(arr3, item)

5 个答案:

答案 0 :(得分:3)

这样的东西?

def eliminate from, item
  from.reject { |e| e.include? item.join } &
  from.reject { |e| e.include? item.join.reverse }
end

eliminate arr3, item
# ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"]

或者这个!

def eliminate from, item
  from.reject do |e|
    e.include?(item.join) || e.include?(item.join.reverse)
  end
end

eliminate arr3, item
# ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"]

答案 1 :(得分:2)

将条件更改为and

from.select { |pair| !pair.include? item1 and !pair.include? item2} 

答案 2 :(得分:2)

由于您的情况,您的代码无法正常工作:

!pair.include? item1 or !pair.include? item2

你有条件"倒退"因为您使用or代替and。你想要其中一个:

!pair.include?(item1) && !pair.include?(item2)
# or
!(pair.include?(item1) || pair.include?(item2))

这是因为De Morgan's boolean conversion laws。我们假设您有两个条件AB。然后

not(A or B) = not(A) and not(b)
not(A and B) = not(A) or not(B)

您希望pair不包含item1 item2,这就是原因:

!pair.include?(item1) && !pair.include?(item2)

是一种自然而正确的表达方式。

答案 3 :(得分:1)

不雅但有效(" brutto ma buono"):

arr3 = ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "Dd,Da,Dc", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC", "dD,dC,dA"]
item = ["dD"]
result = arr3.delete_if do |element|
  triad = element.split(",")
  triad.member?(item[0]) or triad.member?(item[0].reverse)
end
p result

答案 4 :(得分:0)

arr3.reject { |str| str =~ /#{item.first}|#{item.first.reverse}/ }
  #=> ["Ac,Ab,Aa", "Ba,Bb,Bd", "Ca,Cc,Cb", "aA,aC,aD", "bD,bA,bB", "cB,cA,cC"]