Tree-sitter Ruby Grammar
tree-sitter-ruby provides the Ruby grammar for the Tree-sitter parsing library. It enables Python applications to parse Ruby source code into concrete syntax trees. The library is actively maintained, with version 0.23.1 being the current stable release, and new versions are released periodically to update grammar rules or address issues.
Warnings
- breaking The `Language.build_library` method was removed around `py-tree-sitter` version 0.21.x. Attempting to use it will raise an AttributeError.
- gotcha The `parser.parse()` method expects source code as a `bytes` object, not a standard Python string. Passing a string will result in a `TypeError` or unexpected parsing behavior.
- gotcha While `tree-sitter-ruby` provides the Ruby grammar, the core parsing functionality (e.g., `Parser` class, `Language` class) is provided by the `tree-sitter` PyPI package. Both need to be installed.
Install
-
pip install tree-sitter tree-sitter-ruby
Imports
- Language
from tree_sitter import Language
- Parser
from tree_sitter import Parser
- tsruby.language()
import tree_sitter_ruby as tsruby RUBY_LANGUAGE = Language(tsruby.language())
Quickstart
import tree_sitter_ruby as tsruby
from tree_sitter import Language, Parser
# Load the Ruby language grammar
RUBY_LANGUAGE = Language(tsruby.language())
# Create a parser and set its language
parser = Parser()
parser.set_language(RUBY_LANGUAGE)
# Ruby code to parse (must be bytes)
ruby_code = b"""
def hello_world(name)
puts "Hello, #{{name}}!"
end
hello_world("Alice")
"""
# Parse the code
tree = parser.parse(ruby_code)
# Get the root node of the syntax tree
root_node = tree.root_node
print(f"Root node type: {root_node.type}")
print(f"Number of children: {len(root_node.children)}")
# Example of traversing a child node
if root_node.children:
first_child = root_node.children[0]
print(f"First child type: {first_child.type}, text: {first_child.text.decode('utf8')}")