0
g = [["xx", "A"],­ ["xx", "B"]]­
g.any?{­|x,y| y.eq­l? ("A"|­|"B"||"C"­)}

我想评估子数组中的第二个元素是否是“A”或“B”或“C”之一。在上述情况下,它应该返回true. 并返回false,例如,if g=[["xx","K"]["xx","B"]

4

4 回答 4

5

怎么样:

g.all? { |x,y| y =~ /^(A|B|C)$/ }

编辑:@PriteshJ 观察后

于 2012-07-28T08:01:13.683 回答
1

我想总是("A" || "B" || "C")给你"A"

  g.each{|x, y| puts "ABC".include? y}
于 2012-07-28T08:01:23.450 回答
0

看起来好的旧哈希比正则表达式更快:

require 'benchmark'

many = 500000

g = [["x", "A"], ["xx", "B"]]
h = {"A" => true, "B" => true, "C" => true}
Benchmark.bm do |b|
  b.report("regexp") { many.times { g.all? { |x,y| y =~ /^(A|B|C)$/ } } }
  b.report("hash") { many.times { g.all? { |x,y| h.has_key?(y) } } }
end

# regexp  1.690000   0.000000   1.690000 (  1.694377)
# hash  1.040000   0.000000   1.040000 (  1.040016)
于 2012-07-28T12:57:57.423 回答
0

我想出了以上两个答案的组合

1.9.3p194 :177 > g =[["xx", "A"],["xx", "B"]]
 => [["xx", "A"], ["xx", "B"]] 
1.9.3p194 :178 > g.all?  {|i,v| "ABC".include?v}
 => true  #correctly return true
1.9.3p194 :179 > g =[["xx", "A"],["xx", "Ba"]]
 => [["xx", "A"], ["xx", "Ba"]] 
1.9.3p194 :180 > g.all?  {|i,v| "ABC".include?v}
 => false #correctly return false

编辑基准测试后受@victor 的回答启发

array= ['A','B','C']
g.all? { |x,y| arr.include?y

h = {"A" => true, "B" => true, "C" => true}
g.all? { |x,y| h.has_key?(y)

是赢家。

Benchmark 的灵感来自@victor 答案

require 'benchmark'

many = 500000

g = [["x", "A"], ["xx", "B"]]
h = {"A" => true, "B" => true, "C" => true}
arr = ['A','B','C']

Benchmark.bm do |b|
  b.report("regexp1\t") {many.times { g.all? { |x,y| y =~ /^(A|B|C)$/} } }
  b.report("regexp2\t") { many.times { g.all? { |x,y| y =~ /^[ABC]$/ } } }
  b.report("hash\t") { many.times { g.all? { |x,y| h.has_key?(y) } } }
  b.report("str include\t") { many.times { g.all? { |x,y| "ABC".include?y } } }
  b.report("array include\t") { many.times { g.all? { |x,y| arr.include?y } } }
end

#Output 
       user     system      total        real
regexp1           0.640000   0.000000   0.640000 (  0.635750)
regexp2           0.580000   0.000000   0.580000 (  0.586788)
hash              0.370000   0.000000   0.370000 (  0.364140)
str include       0.430000   0.010000   0.440000 (  0.439753)
array include     0.380000   0.010000   0.390000 (  0.381149)

干杯。

于 2012-07-28T09:00:46.767 回答