Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I developed a QuickIndex class which serves to index arrays of stringafiable objects using a tree structure. The purpose is to then primarily to allow for fast index or include? method calls directed to the quick_index object as a proxy for the original array, as the index tree can be traversed much more efficiently than a linear array.

There is a gist containing the whole class, but the main functionality comes from the two methods included below.

class QuickIndex
  def initialize ary, stop_char = "!"
    @stop_char = stop_char
    @size = ary.size
    @index = Hash.new
    ary.each_with_index do |num, i|
      num = num.to_s.split("") << @stop_char
      index = @index
      until num.empty?
        n = num.shift
        index = index[n] ||= (n == @stop_char ? [] : {})
      end
      index << i
    end
  end

  def index item
    index = @index
    (item.to_s.split("") << @stop_char).each { |n| next unless index = (index[n] or nil rescue nil) }
    index
  end
end

The stop_char is a single character which serves to indicate the end of a string in the index.

The class is specifically intended for locating specific values in very large (NArray) arrays of ints or floats, but it's nice for it to work with other objects too.

It works reasonably well, but I'd like to know of any optimisations or alternative strategies to this problem which would make the class quicker at either building or querying the index and/or reduce the memory footprint. Or if there's some standard library alternative I've overlooked...

share|improve this question

Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.