In Files

  • scanf.rb

Parent

Sections

Class/Module Index [+]

Quicksearch

String

scanf ↑ top

Public Instance Methods

block_scanf(fstr) click to toggle source

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 #block_scanf

 
               # File 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) click to toggle source

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 #scanf

 
               # File 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
            

Commenting is here to help enhance the documentation. For example, code samples, or clarification of the documentation.

If you have questions about Ruby or the documentation, please post to one of the Ruby mailing lists. You will get better, faster, help that way.

If you wish to post a correction of the docs, please do so, but also file bug report so that it can be corrected for the next release. Thank you.

If you want to help improve the Ruby documentation, please visit Documenting-ruby.org.

blog comments powered by Disqus