This question already has an answer here:
这个问题在这里已有答案:
- How to sort an array in Ruby to a particular order? 3 answers
如何将Ruby中的数组排序为特定的顺序? 3个答案
I have two arrays
我有两个数组
ordered = [1, 2, 3, 4, 5]
some_list = [2, 6, 4]
I would like to compare the two arrays, then find the duplicates, and form it into a new array. The trick is to keep the array in the order provided in the ordered
array.
我想比较两个数组,然后找到重复项,并将其形成一个新数组。诀窍是按照有序数组中提供的顺序保持数组。
new_array = [2, 4] # Result should be this
I've thought of one way to do it, however I think the performance can be improved.
我想过一种方法,但我认为性能可以提高。
ordered.each do |value1|
some_list.include? value1
new_array << value1
end
end
Is there any way I can improve this?
有什么办法可以改善吗?
Benchmark results
user system total real
using & 0.210000 0.000000 0.210000 ( 0.212070)
using select 0.220000 0.000000 0.220000 ( 0.218889)
3 个解决方案
#1
4
Try this new_arry = ordered & some_list
试试这个new_arry = ordered&some_list
#2
2
It can also be done in following way:
它也可以通过以下方式完成:
uniques = ordered - some_list
duplicates = ordered - uniques
Order will be preserved.
订单将被保留。
Refer: http://ruby-doc.org/core-2.0.0/Array.html#method-i-2D
#3
1
ordered.select{|i| some_list.include?(i)}
Edit:
Not really sure if select is optimised for performance, but it is provided as shorter and clear alternative to the code provided by the OP.
不确定select是否针对性能进行了优化,但它是作为OP提供的代码的更短且更清晰的替代方式提供的。
A quick benchmark gave this results: Edit: adding the accepted answer alternative.
快速基准测试给出了以下结果:编辑:添加接受的答案替代方案。
user system total real
each 0.000000 0.000000 0.000000 ( 0.000005)
select 0.000000 0.000000 0.000000 ( 0.000004)
& 0.000000 0.000000 0.000000 ( 0.000005)
#1
4
Try this new_arry = ordered & some_list
试试这个new_arry = ordered&some_list
#2
2
It can also be done in following way:
它也可以通过以下方式完成:
uniques = ordered - some_list
duplicates = ordered - uniques
Order will be preserved.
订单将被保留。
Refer: http://ruby-doc.org/core-2.0.0/Array.html#method-i-2D
#3
1
ordered.select{|i| some_list.include?(i)}
Edit:
Not really sure if select is optimised for performance, but it is provided as shorter and clear alternative to the code provided by the OP.
不确定select是否针对性能进行了优化,但它是作为OP提供的代码的更短且更清晰的替代方式提供的。
A quick benchmark gave this results: Edit: adding the accepted answer alternative.
快速基准测试给出了以下结果:编辑:添加接受的答案替代方案。
user system total real
each 0.000000 0.000000 0.000000 ( 0.000005)
select 0.000000 0.000000 0.000000 ( 0.000004)
& 0.000000 0.000000 0.000000 ( 0.000005)