Class: Scanf::FormatString

Inherits:
Object
  • Object
show all
Defined in:
lib/scanf.rb

Constant Summary collapse

SPECIFIERS =
'diuXxofeEgsc'
REGEX =
/
        # possible space, followed by...
          (?:\s*
          # percent sign, followed by...
            %
            # another percent sign, or...
(?:%|
        	 # optional assignment suppression flag
        	 \*?
        	 # optional maximum field width
        	 \d*
        	   # named character class, ...
        	   (?:\[\[:\w+:\]\]|
        	   # traditional character class, or...
 \[[^\]]*\]|
        	   # specifier letter.
 [#{SPECIFIERS}])))|
            # or miscellaneous characters
[^%\s]+/ix

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(str) ⇒ FormatString

Returns a new instance of FormatString.



514
515
516
517
518
519
520
521
# File 'lib/scanf.rb', line 514

def initialize(str)
  @specs = []
  @i = 1
  s = str.to_s
  return unless /\S/.match(s)
  @space = true if /\s\z/.match(s)
  @specs.replace s.scan(REGEX).map {|spec| FormatSpecifier.new(spec) }
end

Instance Attribute Details

#last_match_triedObject (readonly)

Returns the value of attribute last_match_tried



490
491
492
# File 'lib/scanf.rb', line 490

def last_match_tried
  @last_match_tried
end

#last_spec_triedObject (readonly)

Returns the value of attribute last_spec_tried



490
491
492
# File 'lib/scanf.rb', line 490

def last_spec_tried
  @last_spec_tried
end

#matched_countObject (readonly)

Returns the value of attribute matched_count



490
491
492
# File 'lib/scanf.rb', line 490

def matched_count
  @matched_count
end

#spaceObject (readonly)

Returns the value of attribute space



490
491
492
# File 'lib/scanf.rb', line 490

def space
  @space
end

#string_leftObject (readonly)

Returns the value of attribute string_left



490
491
492
# File 'lib/scanf.rb', line 490

def string_left
  @string_left
end

Instance Method Details

#last_specObject



535
536
537
# File 'lib/scanf.rb', line 535

def last_spec
  @i == spec_count - 1
end

#match(str) ⇒ Object



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
# File 'lib/scanf.rb', line 539

def match(str)
  accum = []
  @string_left = str
  @matched_count = 0

  @specs.each_with_index do |spec,@i|
    @last_spec_tried = spec
    @last_match_tried = spec.match(@string_left)
    break unless @last_match_tried
    @matched_count += 1

    accum << spec.conversion

    @string_left = @last_match_tried.post_match
    break if @string_left.empty?
  end
  return accum.compact
end

#prune(n = matched_count) ⇒ Object



527
528
529
# File 'lib/scanf.rb', line 527

def prune(n=matched_count)
  n.times { @specs.shift }
end

#spec_countObject



531
532
533
# File 'lib/scanf.rb', line 531

def spec_count
  @specs.size
end

#to_sObject



523
524
525
# File 'lib/scanf.rb', line 523

def to_s
  @specs.join('')
end