B Seven
B Seven

Reputation: 45943

How to set up data structure for efficient search in Ruby?

I have an array of hashes. Each hash looks like:

'date'=>6/23/2011, value1=>6, value2=>8, value3=>3, value4=>6

The array has about 10,000 hash elements.

Is there a built-in way in Ruby to efficiently find by the index of an element by date? I know there is Array.index but does it iterate through the array sequentially?

Is there a better way to set up my data so that it can be accessed efficiently?

Ruby 1.9.3

Upvotes: 3

Views: 557

Answers (1)

Darshan Rivka Whittle
Darshan Rivka Whittle

Reputation: 34031

It sounds like you're doing it backwards. You should have a hash of arrays:

{'6/23/2011' => [6, 8, 3, 6]}

That way, given a date, you have constant-time access to the corresponding data. It also gives you cleaner access to the values, rather than the clumsy 'valueX' stuff.

Upvotes: 12

Related Questions