oaklodge oaklodge - 10 months ago 55
Ruby Question

Parse Ruby file for comments

I want something that can parse a ruby file to give me the file positions of comments. Ranked by desirability:

  1. Ideally, there would be some command-line arg I could pass to "ruby" since of course "ruby" would know. But there doesn't seem to be one for this?

  2. Does anyone know if/where in "ruby" I could hook in and use its methods to know where the comments are?

  3. Some well-known regular expression?



Found: https://github.com/ruby/ruby/tree/trunk/ext/ripper


require 'ripper'
require 'pp'

class CommentRipper < Ripper::SexpBuilder
    def on_comment(token)
        super.tap { |result| pp result }

contents = File.read("file.rb")
pp CommentRipper.new(contents).parse

Helped me understand Ripper better: http://svenfuchs.com/2009/7/5/using-ruby-1-9-ripper