Tree-sitter Ruby Grammar

0.23.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to initialize the Ruby grammar with `tree-sitter`, create a parser, and parse a simple Ruby code snippet. It shows how to access the root of the resulting syntax tree and some basic node properties.

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')}")

view raw JSON →