Afficher un message
Vieux 13/03/2008, 02h59   #3
Thomas Wieczorek
Aucun Avatar
 
Messages: n/a
Hébergeur:
Par défaut Re: String method to take subsections

On Thu, Mar 13, 2008 at 1:18 AM, Glenn <glenn_ritz@yahoo.com> 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')

  Réponse avec citation
 
Page generated in 0,05316 seconds with 9 queries