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



748
749
750
751
752
753
754
755
756
757
758
# File 'lib/scanf.rb', line 748

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



715
716
717
718
719
720
721
722
723
724
725
726
727
# File 'lib/scanf.rb', line 715

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