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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9313957/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-06 04:46:15  来源:igfitidea点击:

Fastest way to find a String into an array of string

rubyarraysstringloopscomparison

提问by Cocotton

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)

该脚本必须验证一个预定义的 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

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?

编辑:我可能错误地表达了自己。我可以做array.include吗?但我想知道的是:是array.include吗?能给我最快结果的方法是什么?

回答by Aliaksei Kliuchnikau

You can use Set. It is implemented on top of Hash and will be faster for big datasets - O(1).

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

回答by ericraio

You could use the Array#include method to return you a true/false.

您可以使用 Array#include 方法返回真/假。

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

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

回答by Don Cruickshank

A faster way would be:

更快的方法是:

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

回答by Peter Ehrlich

have you tried the Array#include? function?

你试过 Array#include 吗?功能?

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

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.

您可以从源代码中看到它几乎完全相同,除了本机。

回答by dku.rajkumar

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

在此处查看文档