这怎么样 ?
groups = [
["G1", ["A0640", "A0660", "A0647", "A0643", "A0604", "A0644"]],
["G2", ["A1609","A1611","A1608","A1610"]],
["G3", ["A0613", "A0619", "A0637", "A0636"]],
["G4", ["A0646", "A0610", "A0645"]],
["G5", ["A0616", "A0611", "A0638", "A0606", "A0602", "A0639", "A0626", "A0605"]]
]
Hash[groups].detect{|_,v| v.include? "A0619" }.first
# => "G3"
更新
groups = [
["G1", ["A0640", "A0660", "A0647", "A0643", "A0604", "A0644"]],
["G2", ["A1609","A1611","A1608","A1610"]],
["G3", ["A0613", "A0619", "A0637", "A0636"]],
["G4", ["A0646", "A0610", "A0645"]],
["G5", ["A0616", "A0611", "A0638", "A0606", "A0602", "A0639", "A0626", "A0605"]]
]
groups[groups.index{|_,a| a.include? "A0619"}][0]
# => "G3"
基准
require "benchmark"
groups = [
["G1", ["A0640", "A0660", "A0647", "A0643", "A0604", "A0644"]],
["G2", ["A1609","A1611","A1608","A1610"]],
["G3", ["A0613", "A0619", "A0637", "A0636"]],
["G4", ["A0646", "A0610", "A0645"]],
["G5", ["A0616", "A0611", "A0638", "A0606", "A0602", "A0639", "A0626", "A0605"]]
]
Benchmark.bm(8) do |x|
x.report("falsetru:") do
1_000_000.times { groups.detect{|x,y| y.detect{|o| o == "A0619"} }[0] }
end
x.report("Arup1") do
1_000_000.times { groups[groups.index{|_,a| a.include? "A0619"}][0] }
end
x.report("Arup2") do
1_000_000.times do
Hash[groups].detect{|_,v| v.include? "A0619" }.first
end
end
end
输出
user system total real
falsetru: 8.860000 0.000000 8.860000 ( 8.885295)
Arup1 2.780000 0.000000 2.780000 ( 2.800791)
Arup2 7.800000 0.000000 7.800000 ( 7.825369)