class URITemplate::RegexpEnumerator
An awesome little helper which helps iterating over a string. Initialize with a regexp and pass a string to :each. It will yield a string or a MatchData
Public Class Methods
new(regexp, options = {})
click to toggle source
# File lib/uri_template/utils.rb, line 32 def initialize(regexp, options = {}) @regexp = regexp @rest = options.fetch(:rest){ :yield } end
Public Instance Methods
each(str) { |rest| ... }
click to toggle source
# File lib/uri_template/utils.rb, line 37 def each(str) raise ArgumentError, "RegexpEnumerator#each expects a String, but got #{str.inspect}" unless str.kind_of? String return self.to_enum(:each,str) unless block_given? rest = str loop do m = @regexp.match(rest) if m.nil? if rest.size > 0 yield rest end break end yield m.pre_match if m.pre_match.size > 0 yield m if m[0].size == 0 # obviously matches empty string, so post_match will equal rest # terminate or this will loop forever if m.post_match.size > 0 yield m.post_match if @rest == :yield raise "#{@regexp.inspect} matched an empty string. The rest is #{m.post_match.inspect}." if @rest == :raise end break end rest = m.post_match end return self end