找到一个字符串到字符串数组最快的方法 [英] Fastest way to find a String into an array of string
问题描述
该脚本来验证,如果一个predefined IP是IP地址的一个大数组present。目前我code的功能类似这样(说IPS是我的IP阵列和IP是predefined IP)
The script has to verify if one predefined IP is present in a big array of IPs. Currently I code that function like this (saying that "ips" is my array of IP and "ip" is the predefined ip)
ips.each do |existsip|
if ip == existsip
puts "ip exists"
return 1
end
end
puts "ip doesn't exist"
return nil
有没有更快的方式做同样的事情?
Is there a faster way to do the same thing?
编辑:我可能有错误的前pressed自己。我可以做array.include?但我想知道的是:是array.include?这将使我最快结果的方法?
Edit : I might have wrongly expressed myself. I can do array.include? but what I'd like to know is : Is array.include? the method that will give me the fastest result?
推荐答案
您可以使用的设置。这是哈希的基础上实现,将是更快的数据集大 - O(1)
You can use Set. It is implemented on top of Hash and will be faster for big datasets - O(1).
require 'set'
s = Set.new ['1.1.1.1', '1.2.3.4']
# => #<Set: {"1.1.1.1", "1.2.3.4"}>
s.include? '1.1.1.1'
# => true
这篇关于找到一个字符串到字符串数组最快的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!