So the question is, how can I check if a horse is included in my array so that I don't fill it with the same horse?
While the answers are related to looking at the array to see if a particular row or object exists, is this really happening incorrectly, because as the array grows, the search will take longer.
Use either Hash or Set instead. Both allow only one instance of a specific item. The set will behave closer to the array, but allows only one instance. This is a more proactive approach that avoids duplication due to 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 # => #<Set: {"a", "b"}> ary << 'a' ary # => #<Set: {"a", "b"}>
Hash uses name / value pairs, which means the values ββwill not have real use, but it seems to be a bit more speed using 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
What outputs:
user system total real Hash 8.140000 0.130000 8.270000 ( 8.279462) Array 10.680000 0.120000 10.800000 ( 10.813385)
the Tin Man Jun 29 '13 at 5:01 2013-06-29 05:01
source share