我想知道让String.include?
种方法忽略 case 的最佳方法是什么.目前我正在做以下工作.有什么建议吗?谢谢
a = "abcDE"
b = "CD"
result = a.downcase.include? b.downcase
编辑:
我想知道让String.include?
种方法忽略 case 的最佳方法是什么.目前我正在做以下工作.有什么建议吗?谢谢
a = "abcDE"
b = "CD"
result = a.downcase.include? b.downcase
编辑:
如果你只想用数组测试一个单词,或者数组的内容经常变化,最快的答案是Aaron的:
array.any?{ |s| s.casecmp(mystr)==0 }
如果你想用一个静态数组测试很多单词,最好使用farnoy答案的变体:创建一个包含所有小写单词的数组副本,然后使用include?
.(这假设您可以腾出内存来创建数组的变异副本.)
# Do this once, or each time the array changes
downcased = array.map(&:downcase)
# Test lowercase words against that array
downcased.include?( mystr.downcase )
更好的是,从你的数组中创建一个Set
.
# Do this once, or each time the array changes
downcased = Set.new array.map(&:downcase)
# Test lowercase words against that array
downcased.include?( mystr.downcase )
My original answer below is a very poor performer and generally not appropriate.
以下是在10万多个单词的数组中随机搜索1000个单词的基准测试,其中500个单词会被找到,500个不会.
any?
.any?
.Set
. user system total real
regex 18.710000 0.020000 18.730000 ( 18.725266)
casecmp 5.160000 0.000000 5.160000 ( 5.155496)
downarray 16.760000 0.030000 16.790000 ( 16.809063)
downonce 0.650000 0.000000 0.650000 ( 0.643165)
set_once 0.040000 0.000000 0.040000 ( 0.038955)
如果您可以创建一个数组的下壳副本,对其执行多次查找,farnoy的答案是最好的(假设您使用一个数组).不过,如果你能创造一个Set
,那就这么做吧.
如果你愿意,examine the benchmarking code美元.
I (originally said that I)会亲自创建一个不区分大小写的正则表达式(用于字符串文字),并使用它:
re = /\A#{Regexp.escape(str)}\z/i # Match exactly this string, no substrings
all = array.grep(re) # Find all matching strings…
any = array.any?{ |s| s =~ re } # …or see if any matching string is present
使用any?
可以比使用grep
稍微快一些,因为它可以在找到一个匹配项后立即退出循环.