Ruby under the microscope
This section looks inside Ruby: what happens to your code between ▶ and the answer. The idea – and the phrase – come from the book Ruby Under a Microscope by Pat Shaughnessy (No Starch Press, 2013), which explains Ruby's internals with diagrams and experiments. The book is his work; these lessons were not written by him and are not connected to it. If you like this section, read the book – it goes much deeper.
Every claim here was checked twice: in CRuby's own source code, at the exact version this page runs (links to github.com/ruby/ruby at tag v4.0.0), and by running it right here. And "right here" matters, because this Ruby is unusual:
RUBY_DESCRIPTIONwasm32-wasi: CRuby compiled to WebAssembly with 32-bit pointers. Most explanations of Ruby's internals assume a 64-bit laptop; where wasm32 is different, these lessons show both. +PRISM names the parser. Ruby reads your code in three steps: the lexer cuts the text into tokens, the parser builds a tree from them, and the compiler turns the tree into instructions for YARV, Ruby's virtual machine. Step one:
show_tokens("total = price * 2 if hungry?")Each chip is one token: its text, and below it the type Prism gave it. The lexer already knows more than letters: hungry? is a METHOD_NAME (a local variable cannot end in ?), and this if is a KEYWORD_IF_MODIFIER, not the if that starts a line. Step two, the parser:
show_ast("total = price * 2 if hungry?")The if you wrote last is the root of the tree: the condition is checked first, the assignment is its body. price * 2 is a Call – the method * sent to price, with 2 as its argument. And price is a Call too: nothing assigned it before, so for Ruby it can only be a method. Prism is a gem as well, and its tree is made of Ruby objects. It also keeps going after a mistake and reports all of them:
require "prism"
result = Prism.parse("1 +* 2")
result.errors.map(&:message)- The lexer and parser:
pm_parse:22271– Prism is one C file of 22,000+ lines, also used by JRuby and TruffleRuby. - The compiler from Prism's tree to YARV:
pm_compile_node:8615.
Prism::Visitor walks the tree and calls visit_call_node(node) for every Call. Define it in CallCounter: add one to @calls – and call super, or the walk stops at that node and misses the calls inside it. count_calls("puts [1, 2].map { |x| x * 2 }.sum") should give 4.require "prism"
class CallCounter < Prism::Visitor
attr_reader :calls
def initialize
@calls = 0
end
# visit_call_node(node): one more call, then super
end
def count_calls(code)
counter = CallCounter.new
Prism.parse(code).value.accept(counter)
counter.calls
end
count_calls("puts [1, 2].map { |x| x * 2 }.sum")4: puts, map, * and sum. The x in the block is a parameter, a local variable – not a call. The next lesson takes the tree one step further: to the instructions YARV runs.