From: Dave Thomas Date: 2001-05-11T13:38:11+09:00 Subject: [ruby-talk:14975] Re: Array search idiom "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] Regards Dave