在字符串数组中查找字符串的最快方法

发布于 2025-01-07 00:13:28 字数 333 浏览 0 评论 0原文

该脚本必须验证一个预定义的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

百思不得你姐 2025-01-14 00:13:28

您可以使用设置。它是在哈希之上实现的,对于大数据集会更快 - 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 

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 
江心雾 2025-01-14 00:13:28

您可以使用 Array#include 方法返回 true/false。

http://ruby-doc.org/core -1.9.3/Array.html#method-i-include-3F

if ips.include?(ip) #=> true
  puts 'ip exists'
else
  puts 'ip  doesn\'t exist'
end

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

if ips.include?(ip) #=> true
  puts 'ip exists'
else
  puts 'ip  doesn\'t exist'
end
请叫√我孤独 2025-01-14 00:13:28

更快的方法是:

if ips.include?(ip)
  puts "ip exists"
  return 1
else
  puts "ip doesn't exist"
  return nil
end

A faster way would be:

if ips.include?(ip)
  puts "ip exists"
  return 1
else
  puts "ip doesn't exist"
  return nil
end
过度放纵 2025-01-14 00:13:28
ips = ['10.10.10.10','10.10.10.11','10.10.10.12']

ip = '10.10.10.10'
ips.include?(ip) => true

ip = '10.10.10.13'
ips.include?(ip) => false

在此处查看文档

ips = ['10.10.10.10','10.10.10.11','10.10.10.12']

ip = '10.10.10.10'
ips.include?(ip) => true

ip = '10.10.10.13'
ips.include?(ip) => false

check Documentaion here

黒涩兲箜 2025-01-14 00:13:28

你尝试过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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文