Our Daily Method #17: Enumerable#make_index

Geplaatst door Michiel de Mare wo, 27 feb 2008 08:03:00 GMT

Do you know what I like so much about relational databases? And what I really miss in object-models? That databases make it so effortless to index data.

Imagine, you’ve got a huge pile of data, unordered, continually changing, but because your database keeps a few indexes, you can access any item you wish within a few milliseconds.

Wouldn’t it be fun if you could do that in Ruby? Especially the effortless part? It happens regularly that I’ve got an array with hundreds of items in which I have to search. That quicky gets slow, so I create a few hashes that I use as indexes. But what a difference with a real database!

Let make a first step in the right direction, and implement the make_index method.

module Enumerable
  def make_index(*names)
    Struct.new(*names).new(*names.map{|n| group_by(&n)})

index = User.find(:all).make_index(:login, :id, :nickname)

index.login['mdemare'] => [<#User ...>]
index.nickname['Michiel'] => [<#User ...>]

I admit, not a huge improvement yet. But we’re getting there. For another time, indexes on more than one attribute, unique indexes and indexing attributes with a natural order. (index.created_at > Time.now.at_midnight)

Geplaatst in , ,  | geen reacties


(Laat url/e-mail achter »)