Fastest way to find a String into an array of string

前端 未结 5 1678
被撕碎了的回忆
被撕碎了的回忆 2021-02-12 18:18

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

相关标签:
5条回答
  • 2021-02-12 18:24
    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

    0 讨论(0)
  • 2021-02-12 18:28

    A faster way would be:

    if ips.include?(ip)
      puts "ip exists"
      return 1
    else
      puts "ip doesn't exist"
      return nil
    end
    
    0 讨论(0)
  • 2021-02-12 18:34

    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 
    
    0 讨论(0)
  • 2021-02-12 18:40

    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
    
    0 讨论(0)
  • 2021-02-12 18:46

    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.

    0 讨论(0)
提交回复
热议问题