2

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?

Thanks!

Wayne Conrad
  • 103,207
  • 26
  • 155
  • 191
oaklodge
  • 722
  • 6
  • 19
  • Hi, get us some input and expected output and maybe some code you tried. You can read this article to improve your answer http://stackoverflow.com/help/how-to-ask – Lukas Baliak Aug 08 '16 at 08:12
  • The input is any ruby file with comments. The output can be of any form as long as I can derive the file positions of comments. I naively started with a regexp like /\#.*/ but quickly realized it was more complicated than that (e.g. a hashtag embedded in a string). I am hoping, and will research later, that I can hook into the "ruby" executable since who should know best, right? Else I will try to adapt the regexp from: http://stackoverflow.com/questions/5865371/ruby-regex-for-finding-comments – oaklodge Aug 08 '16 at 09:55
  • How does one determine what an "off-site resource" is? The how-to-ask link doesn't mention it. – oaklodge Aug 09 '16 at 05:47
  • The [_on-topic_ help page](http://stackoverflow.com/help/on-topic) prohibits reqeusts for "a book, tool, software library, tutorial or other off-site resource." That's all it says, so if that's not clear, then I'd ask for clarification on meta. That would be the first step to getting the help page improved. – Wayne Conrad Aug 09 '16 at 13:52
  • Clue to how complex Ruby comments can be, so regexp will never be able to cover all cases: http://stackoverflow.com/questions/2989762/multi-line-comments-in-ruby – oaklodge Aug 10 '16 at 12:57

1 Answers1

1

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

Example:

require 'ripper'
require 'pp'

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

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

oaklodge
  • 722
  • 6
  • 19