Written by James BrittTechnically reviewed by Jim Freeze · Reviewed
The Ruby Prism parser builds an abstract syntax tree (AST) from Ruby source. It also returns errors, warnings and source locations. You can use it to analyze code, add an editor feature or build a source checker. Parsing describes source; it neither executes it nor tests the logic.
Begin by checking whether parsing succeeded. Then examine the nodes. You can follow these examples without knowing how compilers work. Just keep the source text, its structural representation and the execution environment separate. Confusing them can turn a useful syntax check into a false assurance about runtime behavior.

What the Ruby Prism parser actually does
An abstract syntax tree represents the structure of source code. For an assignment with addition, it identifies a variable write, an addition call and two integer values. This lets an analysis tool distinguish a real method call from the same words used in comments or strings.
Shopify’s account of Prism’s design describes the value of a shared parser. Prism has a C library and Ruby interface, with portability and error tolerance among its goals. Sharing the grammar reduces duplicated work across tools. However, those tools still need their own analyses: a text editor remains different from a compiler.
Prism became a default gem in CRuby 3.3 and the default parser in CRuby 3.4. Those are distinct milestones. A typical application using the standard interpreter need not invoke Prism explicitly. To obtain a syntax tree yourself, load the library and call its API.
Check the Ruby and Prism versions first
Record both versions before comparing a sample with documentation. Ruby and its loaded Prism gem have separate version numbers. Also, Bundler may select a different gem for a project. Reproduce the problem inside that exact bundle before deciding that Prism is behaving incorrectly.
These examples ran with Prism 1.7.0 in the official Ruby 4.0.0 WASI runtime. They establish the illustrated parsing behavior in that environment. They do not establish behavior on newer releases or every Ruby platform. Native extension installation, deployment and parser performance are outside these checks.
For a reusable tool, specify Prism as a dependency and include source samples in your tests. Use syntax from the projects you support. When upgrading, compare diagnostics and the values your traversal reads. Think of the pretty-printed tree as a debugging aid, rather than a permanent format for exchanging data.
require "prism"
p [RUBY_VERSION, Prism::VERSION]
# ["4.0.0", "1.7.0"] in the checked environment
Parse a small assignment
Prism gives you a result object instead of the arithmetic answer. After checking success, look at the first statement in the program. Because this example uses a tiny, known piece of source, that statement is the assignment. A statement is not necessarily the same thing as a line.
The assignment has a name and a value. Its value here is a call node, with an integer receiver and another integer as its argument. Ruby operators participate in method-call syntax, so an addition call is expected. Prism has described the operation without performing it.
Fixed paths help you explore a known tree, but they make fragile traversal code. An empty file has no first statement. A larger file might start with a class or another expression. Therefore, use this path for the example, then inspect node types when processing arbitrary input.
For entry points and node access, consult the official Prism Ruby API guide. Ruby-Doc’s versioned Prism reference also covers the parsing helpers. Keep the source alongside the result: a later warning or suggested edit will need the exact text and range that produced its node.
require "prism"
result = Prism.parse("total = 2 + 3")
p result.success? # true
assignment = result.value.statements.body.first
p assignment.type # :local_variable_write_node
p assignment.name # :total
p assignment.value.name # :+
p assignment.location.slice # "total = 2 + 3"
Ruby Prism parser errors and recovered trees
Prism can provide useful structure even when input is incomplete. An editor benefits from that while someone is typing. However, incomplete input is not necessarily valid Ruby. When a result contains both a tree and errors, finding the root node alone does not validate anything.
Remove everything after the assignment’s equals sign. You get a failed parse, diagnostics and a program node. Messages may differ with each Prism release. Rather than depending on exact wording, test the condition your tool needs. In this case, ask whether the parse succeeded.
Choose an explicit error policy. An editor might show a recovered tree and underline the offending region. In contrast, a source-changing tool should generally refuse invalid input. Recovered or missing nodes can otherwise lead to edits that look reasonable but damage the program.
Separate parsing checks from runtime checks, too. An unknown method can parse successfully because the invocation has correct grammar. Whether its receiver implements that method is a subsequent question. Parsing cannot establish that file access, database queries, permissions or business rules will work properly.
require "prism"
result = Prism.parse("total =")
p result.success? # false
p result.errors.empty? # false
p result.value.class # Prism::ProgramNode
Walk calls with the Ruby Prism parser
A visitor walks the tree and provides hooks for the node types your tool needs. Here it collects call names, starting at the program root and continuing into children. Nested calls are found through traversal, without guessing how far each lies from a top-level statement.
The inherited visitor method continues into receivers and arguments. Call it from the override; stopping instead can miss nested calls. Test nested input straight away. A flat expression with just one call would not reveal this bug, even though your visitor appeared to work.
In the isolated source below, the bare name has no earlier local-variable assignment, so Prism treats it as a call. Collected names are candidates for analysis. They do not prove which class implements a method. For a real rule, inspect receivers, arguments and scope, then create positive and negative fixtures.
require "prism"
class CallNames < Prism::Visitor
attr_reader :names
def initialize
@names = []
end
def visit_call_node(node)
@names << node.name
super
end
end
visitor = CallNames.new
Prism.parse("puts(price.round(2))").value.accept(visitor)
p visitor.names # [:puts, :round, :price]
Predict the result before opening the answer
Consider a checker that accepts input whenever a root syntax node exists. Would it reject the unfinished assignment below? Choose first: does the missing expression stop any tree from being returned, or does Prism return a tree with errors? Open the explanation to compare your choice with the checked result.
require "prism"
result = Prism.parse("total =")
p result.value.class
p result.success?
Reveal the parsing result
Prism returns a program node, but success is false and the errors list is not empty. Therefore, this checker would incorrectly accept the input. Examine the result’s success state before treating the tree as valid. A recovered tree helps diagnose a problem; it does not authorize execution or rewriting.
Source locations, comments and safe edits
A node’s location maps its structure back to the source. Warnings can use this information to point at an expression rather than the entire file. Slicing the assignment’s location returns the original assignment. There is no need to reconstruct the text from node names.
Prism’s length and start offset use bytes. UTF-8 characters can span multiple bytes, so these are not character indices. To retrieve source, use the location’s slice operation. For editor integration, convert offsets into the units its protocol expects. Include accented characters in fixtures; ASCII alone cannot expose this distinction.
When changing source, preserve comments and whitespace. Printing an AST does not ensure that you have recreated the same file. Save the original bytes and collect non-overlapping edits. Afterwards, parse the changed text and run the relevant application tests. A successful parse is only the first check.
Choosing Prism and keeping the scope honest
Prism’s named fields and visitor interface give a new analysis script a useful starting point. However, existing tools built with Ripper or the parser gem may expect different trees. Migration means more than renaming a library. Evaluate adapters, diagnostics and the assumptions behind the rules you retain.
Prism also offers translation support for other parser interfaces. Use it when your tool needs that compatibility, without assuming every incidental detail survives. Likewise, a syntax-version option selects supported grammar behavior. It does not launch the selected Ruby version or test the application’s behavior on it.
Takeaway
Use the Ruby Prism parser to inspect source, diagnose syntax problems and locate code. Start with a small, known expression, then use visitors to traverse larger trees. Keep runtime tests separate. Above all, reject invalid input deliberately instead of assuming that a returned tree proves the program correct.
