从数组中减去元素

时间:2013-04-11 06:54:40

标签: ruby

当减去数组时,我只想删除第一个匹配项。

E.g。

[1,2,3,4,4,4,4,5,5]-[1,2,3,4] # => [5,5]

但我需要:

[4,4,4,5,5]

另一个例子:

[1,2,3,4,4,4,4,5,5]-[1,2,3,5] # => [4, 4, 4, 4]

但结果应为:

[4,4,4,4,5]

有办法做到这一点吗?

2 个答案:

答案 0 :(得分:2)

def remove(array, rejects)
  array = array.dup
  rejects.each {|item| array.delete_at(array.index(item))}
  array
end

用法:

remove([1,2,3,4,4,4,4,5,5], [1,2,3,4])                                                                                                                                                                                     
 => [4, 4, 4, 5, 5]                                                                                                                                                                                                                         
remove([1,2,3,4,4,4,4,5,5], [1,2,3,5])                                                                                                                                                                                     
 => [4, 4, 4, 4, 5]                                                                                                                                                                                                                         

您可以不使用不兼容的rejects来调用它,也不要在方法中添加错误处理。

答案 1 :(得分:0)

尝试下面的内容,它会对你有用。

a = [1,2,3,5]
p [1,2,3,4,4,4,4,5,5].delete_if {|x| a.delete_at(a.index(x)) if a.include? x}
#=> [4, 4, 4, 4, 5]

a = [1,2,3,4]
p [1,2,3,4,4,4,4,5,5].delete_if {|x| a.delete_at(a.index(x)) if a.include? x}
#=> [4, 4, 4, 5, 5]

这里有更多例子来澄清选民:

a = [1,2,3,5]
p [3,4,5,1,2,3,4,4,4,4,5,5].delete_if {|x| a.delete_at(a.index(x)) if a.include? x}
#=> [4, 3, 4, 4, 4, 4, 5, 5]

a = [1,2,4,5]
p [3,4,5,1,2,3,4,4,4,4,5,5].delete_if {|x| a.delete_at(a.index(x)) if a.include? x}
#=> [3, 3, 4, 4, 4, 4, 5, 5]

a = [2,3,5]
p [3,4,5,1,2,3,4,4,4,4,5,5].delete_if {|x| a.delete_at(a.index(x)) if a.include? x}
#=>[4, 1, 3, 4, 4, 4, 4, 5, 5]

a = [1,4,4,5]
p [1,2,3,4,4,4,4,5,5].delete_if {|x| a.delete_at(a.index(x)) if a.include? x}
#=> [2, 3, 4, 4, 5]
相关问题