检查所有子字符串是否包含在另一个字符串数组中

时间:2013-02-12 11:30:18

标签: ruby arrays

我有两个字符串数组

order_items=["2832","3284","9832","9234"]
uri=["orderaccept/order_items/3284/cancel","orderaccept/order_items/9234/cancel"]

我想找到order_items的所有元素,这些元素不属于uri。在这种情况下,它应该返回28329832

随意编辑两个数组的内容。我找不到类似的问题,但如果已经问过,请把我联系起来。

3 个答案:

答案 0 :(得分:2)

order_items.select { |item| uri.none? { |u| u.include?(item) } }

答案 1 :(得分:2)

作为变体:

order_items.select{|i| !uri.join.include? i}

更新

order_items=["2832","3284","9832","9234"]
uri=["orderaccept/order_items/3284/cancel","orderaccept/order_items/9234/cancel"]

require 'benchmark'
joined = uri.join
n = 1_000_000
Benchmark.bm do |x|
  x.report("select:") { n.times do  order_items.select{|i| !uri.join.include? i}; end }
  x.report("reject:") { n.times do  order_items.reject{|i| uri.join.include? i}; end }
  x.report("reject2:") { n.times do  order_items.reject{|i| joined.include? i}; end }
  x.report("none?:") { n.times do  order_items.select { |item| uri.none? { |u| u.include?(item) } }; end }
  x.report("substr:") { n.times do  order_items - uri.map { |e| e.gsub /\D/, '' }; end }
  x.report("subt+substr:") {n.times do order_items - uri.map { |i| i[24..27] }; end }
end

它产生了

               user       system      total        real
select:       4.181000   0.015000   4.196000 (  4.275000)
reject:       3.931000   0.000000   3.931000 (  3.925000)
reject2:      1.388000   0.000000   1.388000 (  1.440000)
none?:        4.462000   0.000000   4.462000 (  4.490000)
substr:       26.582000  0.016000   26.598000( 26.675000)
subt+substr:  3.167000   0.000000   3.167000 (  3.170000)

答案 2 :(得分:0)

我猜数组减法在这里更适用,因为它对未来的代码修订是自我描述的(你确实愿意从数组中减去不必要的项目,不是吗?)

order_items - uri.map { |e| e.gsub /\D/, '' }

UPD Ooups ......基准测试迫使我准确思考,例如它来到:

order_items - uri.map { |i| i[24..27] }

基准:

order_items=["2832","3284","9832","9234"]
uri=["orderaccept/order_items/3284/cancel","orderaccept/order_items/9234/cancel"]

require 'benchmark'
n = 1_000_000
Benchmark.bm do |x|
  x.report("select:") { n.times do  order_items.select{|i| !uri.join.include? i}; end }
  x.report("reject:") { n.times do  order_items.reject{|i| uri.join.include? i}; end }
  x.report("none?:") { n.times do  order_items.select { |item| uri.none? { |u| u.include?(item) } }; end }
  x.report("subt+gsub:") { n.times do order_items - uri.map { |e| e.gsub /\D/, '' }; end }
  x.report("subt+substr:") {n.times do order_items - uri.map { |i| i[24..27] }; end }
end

产量:

       user     system      total        real
select:  7.200000   0.000000   7.200000 (  7.206846)
reject:  6.240000   0.000000   6.240000 (  6.253924)
none?:  9.230000   0.020000   9.250000 (  9.282425)
subt+gsub: 43.440000   0.000000  43.440000 ( 43.491133)
subt+substr:  5.320000   0.010000   5.330000 (  5.333616)