Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 790
B Seven Avatar asked Dec 19 '25 11:12

B Seven


1 Answers

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.

like image 110
Darshan Rivka Whittle Avatar answered Dec 24 '25 08:12

Darshan Rivka Whittle