On Tue, Mar 30, 2010 at 9:16 AM, Derek Cannon
<novellterminator / gmail.com> wrote:
> Hello, everyone! What would be the quickest/best way to check elements
> of an array, which themselves are arrays of hashes? Quick example:
>
> mov1 =3D {"title"=3D>"Batman Returns", "genre"=3D>"Action"}
> mov2 =3D {"title"=3D>"Batman", "genre"=3D>"Action"}
> mov3 =3D {"title"=3D>"Batman Begins", "genre"=3D>"Action"}
> mov4 =3D {"title"=3D>"The Dark Knight", "genre"=3D>"Action"}
> array =3D mov1, mov2, mov3, mov4
>
> Right now, to search for "Batman Beings", for instance, I'm using:
>
> puts array.each { |i|
> =A0if i["title"] =3D=3D "Batman Begins"
> =A0 =A0puts "Found!"
> =A0 =A0break # ends the searching because item is found
> =A0end
> =A0}
>
> Is there a better or faster way to do this in Ruby? I'm going to be
> looking through much more data then this, so I want the most efficient
> code possible. I'm just a beginner, so this is pretty much all I know
> how to do in Ruby.

item =3D array.find {|movie| movie["title"] =3D=3D "Batman Begins"}

If the array is not sorted by the criteria you want to search for, you
will have to traverse the array looking at all elements (O(n)). If you
have a relevant amount of data you should look into using a real
database to do the searching for you with appropriate indexes.

Jesus.