rubyparsingruby-parser

How can I parse multiple lines using ruby_parser?


I'm trying to use ruby_parser to parse some multi-lined Ruby code in a file.

Let's say I want to parse the following code:

def foo
  2 + 2
end

When I do the following I get an error:

RubyParser.new.parse("def foo")
#=> Racc::ParseError: (string):1 :: parse error on value "$end" ($end)

because the line does not contain an end.

I'm passing lines in one at a time using File.readlines(file).

Ideally I would specify the filename to RubyParser, but I can't seem to figure that out, and there's very little documentation.


Solution

  • You cannot pass line by line. Pass the whole code at once.

    RubyParser.new("def foo\n  2 + 2\nend")
    

    or

    RubyParser.new(File.read(file))