From: "Jesús Gabriel y Galán" Date: 2010-10-11T18:36:00+09:00 Subject: Re: Testing for subarrays On Mon, Oct 11, 2010 at 11:27 AM, Michel Demazure wrote: > I want to check whether a given array contains a given subarray and > return the corresponding range. > Is there a builtin method ? If not, do you have better than this : > > class Array >  def look_up(sub_array) >    len = sub_array.size >    self.each_cons(len).with_index do |cons, index| >      return Range.new(index, index + len - 1) if cons == sub_array >    end >    nil >  end > end Not necessarily better: irb(main):001:0> a = [1,2,3,4,5,6,7,8] => [1, 2, 3, 4, 5, 6, 7, 8] irb(main):002:0> b = [4,5,6] => [4, 5, 6] irb(main):004:0> a.each_cons(b.size).to_a.index(b) => 3 irb(main):005:0> a.each_cons(b.size).to_a.index([5,1,2]) => nil Jesus.