Class: String

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

Instance Method Summary collapse

Instance Method Details

#block_scanf(fstr) ⇒ Object

Scans the current string until the match is exhausted yielding each match as it is encountered in the string. A block is not necessary as the results will simply be aggregated into the final array.

"123 456".block_scanf("%d")
# => [123, 456]

If a block is given, the value from that is returned from the yield is added to an output array.

"123 456".block_scanf("%d) do |digit,| # the ',' unpacks the Array
  digit + 100
end
# => [223, 556]

See Scanf for details on creating a format string.

You will need to require ‘scanf’ to use String#block_scanf



753
754
755
756
757
758
759
760
761
762
763
# File 'lib/scanf.rb', line 753

def block_scanf(fstr) #:yield: current_match
  fs = Scanf::FormatString.new(fstr)
  str = self.dup
  final = []
  begin
    current = str.scanf(fs)
    final.push(yield(current)) unless current.empty?
    str = fs.string_left
  end until current.empty? || str.empty?
  return final
end

#scanf(fstr, &b) ⇒ Object

Scans the current string. If a block is given, it functions exactly like block_scanf.

arr = "123 456".scanf("%d%d")
# => [123, 456]

require 'pp'

"this 123 read that 456 other".scanf("%s%d%s") {|m| pp m}

# ["this", 123, "read"]
# ["that", 456, "other"]
# => [["this", 123, "read"], ["that", 456, "other"]]

See Scanf for details on creating a format string.

You will need to require ‘scanf’ to use String#scanf



720
721
722
723
724
725
726
727
728
729
730
731
732
# File 'lib/scanf.rb', line 720

def scanf(fstr,&b) #:yield: current_match
  if b
    block_scanf(fstr,&b)
  else
    fs =
      if fstr.is_a? Scanf::FormatString
        fstr
      else
        Scanf::FormatString.new(fstr)
      end
    fs.match(self)
  end
end