如何使用block/lambda表达式从Ruby中的数组中删除相同值的n个元素?
我正在学习Ruby,我正在尝试用Ruby的方式思考。然而,尽管我尽了最大努力,我还是无法集中精力解决这个问题: 例如,我有以下源阵列:如何使用block/lambda表达式从Ruby中的数组中删除相同值的n个元素?,ruby,lambda,Ruby,Lambda,我正在学习Ruby,我正在尝试用Ruby的方式思考。然而,尽管我尽了最大努力,我还是无法集中精力解决这个问题: 例如,我有以下源阵列: a = [1, 3, 5, 4, 5, 5, 7, 5] # param 1 = number matching, param 2 times matching b = a.remove_repeated(5, 3) 那么b的值是: b = [1, 3, 4, 7, 5] a = [1, 8, 9, 2] 如果我只想匹配两个值,我希望它们也都被删除。例如
a = [1, 3, 5, 4, 5, 5, 7, 5]
# param 1 = number matching, param 2 times matching
b = a.remove_repeated(5, 3)
那么b的值是:
b = [1, 3, 4, 7, 5]
a = [1, 8, 9, 2]
如果我只想匹配两个值,我希望它们也都被删除。例如:
a = [1, 4, 8, 4, 9, 2]
b = a.remove_repeated(4, 3)
那么b的值是:
b = [1, 3, 4, 7, 5]
a = [1, 8, 9, 2]
我知道如何以迭代和递归的方式来实现这一点。更确切地说,我在寻找一种鲁比式的方法。像这样的代码是你想要的吗
class Array
def remove_repeated(item, count)
inject([]) do |filtered, current|
filtered << current unless item==current && (count-=1) >= 0
filtered
end
end
end
a = [1, 3, 5, 4, 5, 5, 7, 5]
p a.remove_repeated(5, 3) # => [1, 3, 4, 7, 5]
a = [1, 4, 8, 4, 9, 2]
p a.remove_repeated(4, 3) # => [1, 8, 9, 2]
Array.reject一次复制一个数组元素,但块为true的元素除外。我不知道为什么要部分删除重复项,但如果要在一个步骤中删除所有重复项:
a = [1, 3, 5, 4, 5, 5, 7, 5]
b = a.uniq
# => a = [1, 3, 5, 4, 5, 5, 7, 5], b = [1, 3, 5, 4, 7]
或
如果要删除的副本没有指定的多,或者根本没有重复,会发生什么情况?例如:使用第一个数组a,但执行a.remove_repeated1,3+1很好的解决方案。你可以交换拒绝!或删除_(如果是破坏性更新)。在使用inject时,可以将状态计数保留在累积的inject[],count]。。。等等