From: Hee-Sob Park Date: 2001-05-11T16:10:10+09:00 Subject: [ruby-talk:14980] Re: Array search idiom "Dave Thomas" wrote in message news:m23dac1ow6.fsf@zip.local.thomases.com... > "James B. Crigler" writes: > > > I need to find the first contiguous list of primates. Assuming the > > array is called "a", here's how I solved the problem. This does > > what I want, but is there a better way? > ... > > a = [ > > "insectivora. shrews", "insectivora. moles", "insectivora. hedgehogs", > > "dermoptera. flying lemurs", "chiroptera. bats", "primates. tree shrews", > > "primates. lemurs", "primates. monkeys", "edentata. sloths", > > "edentata. armadillos", "edentata. anteaters", "pholidota. scaly anteaters", > > "primates. marmosets", "primates. great apes", "primates. humans", > > "lagomorpha. hares", "lagomorpha. rabbits", "lagomorpha. pikas", > > "rodentia. mice", "rodentia. rats" > > ] > > > > first_group_of_primates = Array.new > > a.each do |line| > > next unless line =~ /^primates\./ .. false > > break if line !~ /^primates\./ > > first_group_of_primates.push line > > end > > I don't know if this is better, and it still has the extra pattern > match on the first element of the matching subarray, but it's a > slightly different approach. > > start = len = 0 > pat = /^primates\./ > > start += 1 while a[start] and a[start] !~ pat > len += 1 while a[start+len] =~ pat > > first_group = a[start, len] > Here is another try: pat = /^primates\./ if start = a.index(a.detect{|x|x =~ pat}) last = a.index(a[start+1..-1].detect{|x| x !~ pat}) first_group = last ? a[start...last] : a[start..-1] end > > Regards > > > Dave > Park Hee-Sob