Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest way to find a String into an array of string

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?

like image 522
Cocotton Avatar asked Feb 16 '12 15:02

Cocotton


2 Answers

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 
like image 196
Aliaksei Kliuchnikau Avatar answered Oct 13 '22 20:10

Aliaksei Kliuchnikau


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
like image 27
ericraio Avatar answered Oct 13 '22 19:10

ericraio