2012-07-28 18 views
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"]Ruby如果數組的元素是這些字符之一,則比較

+0

你最好格式化你的代碼,http://meta.stackexchange.com/questions/22186/how-do-i-format -my-code-blocks – xiaowl 2012-07-28 07:53:10

回答

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 

編輯的組合後,通過@勝利者的回答啓發基準

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) 

都是贏家。

基準的通過@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) 

乾杯啓發。

+0

謝謝PriteshJ的所有細節。 – Selvam 2012-07-31 03:14:37

+0

@Selvam用新的基準檢查更新的答案 – PriteshJ 2012-07-31 05:29:48

5

如何:

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

編輯:後@ PriteshJ的觀察

+4

也可以使用/^[ABC] $ /而不是/ ^(A | B | C)$/ – PriteshJ 2012-07-28 09:26:17

1

我覺得("A" || "B" || "C")送花兒給人給你"A"

g.each{|x, y| puts "ABC".include? y} 
+0

謝謝大家。我',在這裏學習一些東西。 – Selvam 2012-07-30 04:37:59

+0

謝謝Xiaowl。 – Selvam 2012-07-31 03:15:16

+0

@Selvam愉快的幫助;-) – xiaowl 2012-07-31 03:24:41

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) 
+0

謝謝莫羅茲先生 – Selvam 2012-07-31 03:14:59

+0

非常酷@Victor莫羅茲檢查我更新的ans我發現了更有趣的東西:) – PriteshJ 2012-07-31 05:22:22

相關問題