Rubellite::Docs::A_GETTING_STARTED::QUICKSTART
Quickstart Guide & Usage Patterns
This guide provides hands-on code examples for embedding Rubellite into your Crystal project, evaluating Ruby scripts, calling Ruby methods with arguments, and executing blocks.
Executive Summary & Key Topics
| Topic | Method / Anchor | Description |
|---|---|---|
| Evaluating Scripts & Invoking Methods | .topic_01_eval_and_methods |
Running code strings and dispatching methods dynamically. |
Related Guides & Source References
- examples/01_basic_eval.cr
- examples/03_calling_ruby_methods_and_blocks.cr
- src/rubellite/value.cr
Class methods
topic_01_eval_and_methods
Evaluating Scripts & Invoking Methods: Running code strings and dispatching methods dynamically.
Rubellite offers high-level helpers on Rubellite and rich methods on Rubellite::Value.
| API Method | Target | Description | ||
|---|---|---|---|---|
| `Rubellite.eval(code)` | Global | Parses and executes a Ruby code string | ||
| `value.call(method, *args)` | Object | Invokes a method on a Ruby object with arguments | ||
| `value.call(method) { | blk | ... }` | Object | Passes a Crystal block to a Ruby method |
Working Examples
require "rubellite"
Rubellite.init
# Define a Ruby class dynamically
Rubellite.eval(<<-RUBY)
class Calculator
def add(a, b)
a + b
end
def transform(list, &block)
list.map(&block)
end
end
RUBY
calc = Rubellite.eval("Calculator.new")
sum = calc.call("add", 15, 27)
puts "Sum: #{sum.to_i64}" # => 42
# Pass a Crystal block to Ruby Enumerable methods
array = Rubellite.eval("[1, 2, 3, 4, 5]")
doubled = array.call("map") do |item|
item.to_i64 * 2
end
Common Pitfalls & Safety Caveats
- Warning: Ruby exceptions raised in eval or call are wrapped into Crystal
Rubellite::Errorexceptions. - Warning: Do not capture long-lived Crystal pointers inside Ruby blocks without pinning.
Frequently Asked Questions (FAQ)
- Q: How do I catch Ruby errors in Crystal?
A: Rescue
Rubellite::Error— it preserves the Ruby exception class name, message, and backtrace.