On Feb 25, 2010, at 11:12 AM, John Smith wrote:
> Question about an array. Say I have the following array...
>
> textlist = ["Apple", "Orange", "Lemon", "Grape", "Orange", "Melon",
> "Orange", "Banana"]
>
> if I did textlist.index("Orage"), I would get "1" returned.
"Orage" #=> nil
"Orange" #=> 1 ;-)

>
> Can anyone tell me how I could retrieve the index number of the 2nd
> instance of "Orange"?
>
> Thanks in advance!

Well, I thought this was a simple answer, but I was remembering
   String#index(string, offset)

something like this:

def textlist.where_is(target)
   locations = []
   each_with_index {|e,i| locations << i if target === e }
   return nil if locations.empty?
   locations
end

textlist.where_is("Orange") #=> [1,4,6]
textlist.where_is("Cherry") #=> nil
textlist.where_is("Grape")  #=> [3]

Define it on Array if you want or in a module to extend any object you  
want.

-Rob

Rob Biedenharn		http://agileconsultingllc.com
Rob / AgileConsultingLLC.com