将String转换为字符串数组的最快方法

该脚本必须validation大量IP中是否存在一个预定义的IP。 目前我的代码function就像这样(说“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? 能给我最快结果的方法吗?

你可以使用Set 。 它是在Hash之上实现的,对于大数据集来说会更快–O(1)。

 require 'set' s = Set.new ['1.1.1.1', '1.2.3.4'] # => # s.include? '1.1.1.1' # => true 

您可以使用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 

更快的方法是:

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

你试过Array #include吗? function?

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

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

 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 

在这里查看Documentaion