From: Thomas Wieczorek Date: 2008-03-13T09:59:55+09:00 Subject: Re: String method to take subsections On Thu, Mar 13, 2008 at 1:18 AM, Glenn wrote: > > So, 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b') would return ["1", "2"]. > You could use String#scan and wrap it in a method or extend the String class: # So, 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b') would return ["1", "2"]. def method_x(str, first, last) pattern = "#{first}(\\d)#{last}" regexp = Regexp.new(pattern) return str.scan(regexp).flatten end p method_x('xxxxxa1byyyyya2bzzzzzzz', 'a', 'b') #=> ["1", "2"]. # you could also extend the String class class String def method_x(first, last) pattern = "#{first}(\\d)#{last}" regexp = Regexp.new(pattern) return self.scan(regexp).flatten end end p 'xxxxxa1byyyyya2bzzzzzzz'.method_x('a', 'b')