Created
October 21, 2011 04:55
-
-
Save vivien/1303130 to your computer and use it in GitHub Desktop.
CodeRay: Iterate on each token with its kind, and its starting line number
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'coderay' | |
class CodeRay::Tokens | |
def each_token | |
lineno = 1 | |
self.each_slice(2) do |token, kind| | |
yield token, kind, lineno | |
lineno += token.count("\n") if token.is_a?(String) | |
end | |
end | |
end | |
__END__ | |
# Example | |
CodeRay.scan_file("path/to/a/file").each_token do |token, kind, line| | |
puts "#{line}: #{token}" if kind == :comment | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
True, because that turned out to be even faster ;)
One 1.8.6-compatible way to iterate over pairs would be this:
But I guess an each_token method would be nice, too.
However, you don't need the Array representation any more: The Scanners call text_token, begin_group etc. on the encoder object, so you can react to them directly. The YAML Encoder demonstrates this.