如何使用块/lambda 表达式从 Ruby 数组中删除 n 个相同值的元素?
我正在学习 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, 4, 8, 4, 9, 2]
b = a.remove_repeated(4, 3)
那么 b 的值将是:
a = [1, 8, 9, 2]
我知道如何以迭代和递归的方式执行此操作。相反,我正在寻找一种 Rubyesque 的方式来做到这一点。
I'm in the process of learning Ruby and I'm trying to think in a Ruby way. However, try as I might, I can't wrap my mind around this problem:
For example, I have the following source array:
a = [1, 3, 5, 4, 5, 5, 7, 5]
# param 1 = number matching, param 2 times matching
b = a.remove_repeated(5, 3)
Then b's value would be:
b = [1, 3, 4, 7, 5]
In the case that there were only two value values that I was trying to match, I would want them all removed as well. Such as:
a = [1, 4, 8, 4, 9, 2]
b = a.remove_repeated(4, 3)
Then b's value would be:
a = [1, 8, 9, 2]
I know how to do this a in both a iterative and a recursive way. Rather, I'm looking for a Rubyesque way of doing it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Array.reject 一次复制数组一个元素,但块为 true 的元素除外。
Array.reject copies the array one element at a time, except for the elements for which the block is true.
您正在寻找类似此代码的内容吗?
Is something like this code what you're looking for?
我不知道为什么你想部分删除重复项,但如果你想在一个步骤中删除所有重复项:
或
I don't know why you want to partially remove the duplicates, but if you want to remove all duplicates in a single step:
or