Saturday, May 16, 2009

Search an Array in Ruby

If you want to search for a value in an array in Ruby you could do something like this:


array = ['Bart','Lisa','Maggie']
array.include?('Homer') # returns false
array.include?('Lisa') # returns true

Another possibility is to do this:


array = ['Bart','Lisa','Maggie']
array.index 'Homer' # returns nil
array.index 'Lisa' # returns 1

Both methods should work for searching an array.

For more information check the Ruby API for the Array Class.


Cheers,

Dani


Find this article also on definenull.com.

2 comments:

Sergio Costa Faria said...

Hi Dani.

But, you didn't commented if I search for "bart" (lowercase) in this array, if it will return something to me. Returns 1 or 0? This array list is case sensitive?

Daniel said...

Hi,

This search is not case sensitive so it will not find 'bart' when 'Bart' is in the array. The command 'array.include?('bart') above will return 'false'.

Cheers