How do I check to see if my array includes an object?

后端 未结 7 1897
刺人心
刺人心 2020-12-04 23:19

I have an array @horses = [] that I fill with some random horses.

How can I check if my @horses array includes a horse that is already incl

7条回答
  •  忘掉有多难
    2020-12-04 23:40

    So the question is how can I check if my array already has a "horse" included so that I don't fill it with the same horse?

    While the answers are concerned with looking through the array to see if a particular string or object exists, that's really going about it wrong, because, as the array gets larger, the search will take longer.

    Instead, use either a Hash, or a Set. Both only allow a single instance of a particular element. Set will behave closer to an Array but only allows a single instance. This is a more preemptive approach which avoids duplication because of the nature of the container.

    hash = {}
    hash['a'] = nil
    hash['b'] = nil
    hash # => {"a"=>nil, "b"=>nil}
    hash['a'] = nil
    hash # => {"a"=>nil, "b"=>nil}
    
    require 'set'
    ary = [].to_set
    ary << 'a'
    ary << 'b'
    ary # => #
    ary << 'a'
    ary # => #
    

    Hash uses name/value pairs, which means the values won't be of any real use, but there seems to be a little bit of extra speed using a Hash, based on some tests.

    require 'benchmark'
    require 'set'
    
    ALPHABET = ('a' .. 'z').to_a
    N = 100_000
    Benchmark.bm(5) do |x|
      x.report('Hash') { 
        N.times {
          h = {}
          ALPHABET.each { |i|
            h[i] = nil
          }
        }
      }
    
      x.report('Array') {
        N.times {
          a = Set.new
          ALPHABET.each { |i|
            a << i
          }
        }
      }
    end
    

    Which outputs:

                user     system      total        real
    Hash    8.140000   0.130000   8.270000 (  8.279462)
    Array  10.680000   0.120000  10.800000 ( 10.813385)
    

提交回复
热议问题