From: Luc Heinrich Date: 2010-02-26T03:39:29+09:00 Subject: Re: Array index question On 25 févr. 2010, at 19:20, David Springer wrote: > textlist = ["Apple", "Orange", "Lemon", "Grape", "Orange", > "Melon","Orange", "Banana"] > > i = textlist.index("Orange") > > if !i.nil? > puts "textlist[" << i.to_s << "] is \"" << textlist[i] << "\"" > j = textlist[i+1,textlist.length-i-1].index("Orange")+i+1 > if !j.nil? > puts "textlist[" << j.to_s << "] is \"" << textlist[j] << "\"" > end > end class Array def indexes_of(obj) indexes = Array.new self.each_with_index {|s,i| indexes << i if s === obj } return indexes end end textlist = ["Apple", "Orange", "Lemon", "Grape", "Orange", "Melon","Orange", "Banana"] p textlist.indexes_of("Orange") #=> [1,4,6] -- Luc Heinrich - luc@honk-honk.com