Class: Scanf::FormatString

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

Constant Summary collapse

SPECIFIERS =
'diuXxofFeEgGscaA'
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


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

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


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

def last_match_tried
  @last_match_tried
end

#last_spec_triedObject (readonly)

Returns the value of attribute last_spec_tried


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

def last_spec_tried
  @last_spec_tried
end

#matched_countObject (readonly)

Returns the value of attribute matched_count


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

def matched_count
  @matched_count
end

#spaceObject (readonly)

Returns the value of attribute space


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

def space
  @space
end

#string_leftObject (readonly)

Returns the value of attribute string_left


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

def string_left
  @string_left
end

Instance Method Details

#last_specObject


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

def last_spec
  @i == spec_count - 1
end

#match(str) ⇒ Object


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

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

  @specs.each_with_index do |spec,i|
    @i=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


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

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

#spec_countObject


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

def spec_count
  @specs.size
end

#to_sObject


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

def to_s
  @specs.join('')
end