在字符串数组中查找字符串的最快方法
该脚本必须验证一个预定义的 IP 是否存在于一大组 IP 中。目前我编写了这样的函数(说“ips”是我的IP数组,“ip”是预定义的ip)
ips.each do |existsip|
if ip == existsip
puts "ip exists"
return 1
end
end
puts "ip doesn't exist"
return nil
是否有更快的方法来做同样的事情?
编辑:我可能错误地表达了自己。我可以做 array.include 吗?但我想知道的是: array.include 是吗?哪种方法能给我最快的结果?
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?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以使用设置。它是在哈希之上实现的,对于大数据集会更快 - O(1)。
You can use Set. It is implemented on top of Hash and will be faster for big datasets - O(1).
您可以使用 Array#include 方法返回 true/false。
http://ruby-doc.org/core -1.9.3/Array.html#method-i-include-3F
You could use the Array#include method to return you a true/false.
http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
更快的方法是:
A faster way would be:
在此处查看文档
check Documentaion here
你尝试过Array#include吗?功能?
http://ruby-doc.org/core -1.9.3/Array.html#method-i-include-3F
您可以从源代码中看到它几乎做了完全相同的事情,除了本机之外。
have you tried the Array#include? function?
http://ruby-doc.org/core-1.9.3/Array.html#method-i-include-3F
You can see from the source it does almost exactly the same thing, except natively.