Coc*_*ton 18 ruby arrays string comparison loops
该脚本必须验证大量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
Run Code Online (Sandbox Code Playgroud)
有没有更快的方法来做同样的事情?
编辑:我可能错误地表达了自己.我可以做array.include吗?但我想知道的是:array.include?能给我最快结果的方法吗?
Ali*_*kau 34
你可以使用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
Run Code Online (Sandbox Code Playgroud)
您可以使用 Array#include 方法返回真/假。
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
Run Code Online (Sandbox Code Playgroud)