PicoRuby: the smallest Ruby
In this lesson your code does not run on CRuby. Every cell goes to PicoRuby.wasm – the Ruby for microcontrollers from the last lesson, here as WebAssembly in a Web Worker of its own, a background thread of the browser. Ask it who it is:
[RUBY_ENGINE, PICORUBY_VERSION, RUBY_PLATFORM]"mruby": since version 4, PicoRuby is built on mruby's VM, and says so. PICORUBY_VERSION is its own version, and wasm32-Emscripten means it was compiled to WebAssembly with Emscripten (ruby.wasm uses WASI). This whole Ruby is 2 MB, 0.9 MB compressed – CRuby's ruby.wasm is 32 MB, 10 MB compressed. On a Raspberry Pi Pico, PicoRuby makes do with 264 KB of memory.
Plain Ruby works as you know it – classes, blocks, string interpolation:
class Fox
attr_reader :name
def initialize(name)
@name = name
end
def greet = "#{name} says: Chunky bacon!"
end
%w[Chunky Bacon].map { |name| Fox.new(name).greet }To stay that small, PicoRuby leaves things out. A method you know from CRuby may simply not be there – respond_to? tells you:
%i[sum tally sort_by group_by zip each_slice inject min max].map do |name|
[name, [3, 1, 2].respond_to?(name)]
endNo sum, tally, sort_by, group_by, zip or each_slice – but inject, min and max are there. Struct and Set are missing, and so are enumerators without a block (each_with_index.map). And integers have 64 bits and stop there: where CRuby moves on to big numbers by itself, PicoRuby raises an error:
big = 2 ** 62
begin
big * 4
rescue RangeError => e
"RangeError: #{e.message}"
endIn return, PicoRuby has things CRuby lacks. A microcontroller has no operating system with threads, so PicoRuby brings its own: Task. Tasks take turns – whenever one waits (sleep_ms, in milliseconds), the next one runs. Here one blinks an LED while the main program reads a sensor:
blink = Task.new do
3.times do |i|
puts "LED #{i.even? ? 'on' : 'off'}"
sleep_ms 100
end
end
3.times do |i|
puts "sensor: #{20 + i} °C"
sleep_ms 100
end
blink.joinOn a real Pico the LED would light up: led = GPIO.new(25, GPIO::OUT), then led.write(1). And a small Ruby need not be a poor one – this PicoRuby brings JSON, YAML, Markdown and even SQLite3:
fox = { name: "Chunky", likes: ["bacon", "Ruby"] }
puts JSON.generate(fox)
db = SQLite3::Database.new(":memory:")
db.execute("CREATE TABLE snacks (name TEXT)")
db.execute("INSERT INTO snacks VALUES ('bacon')")
db.execute("SELECT name FROM snacks")PicoRuby's IRB
On a Pico you talk to PicoRuby through a USB cable and a terminal program: its shell R2P2 knows ls, cat, vim – and irb. Here is an IRB on this PicoRuby: type a line and press Enter. Try [1, 2, 3].sum, 2 ** 70 or a def over several lines – and _, the last answer:
show_irbPicoRuby.wasm needs no installation: one <script> tag puts it into any web page, and <script type="text/ruby"> holds the code. JS leads to the page's JavaScript:
<p id="hello"></p>
<script src="https://cdn.jsdelivr.net/npm/@picoruby/wasm-wasi@latest/dist/init.iife.js"></script>
<script type="text/ruby">
JS.document.getElementById("hello")[:textContent] = "Chunky bacon!"
</script>For a Raspberry Pi Pico there is R2P2, a firmware file you drag onto the board; afterwards the board is a small Ruby computer that a terminal program talks to. How to build and install it is on GitHub.
tally – so write it yourself. count_words(words) gets an array of words and returns a hash with each word and how often it occurs. The last line of the cell, count_words(%w[chunky bacon chunky fox chunky]), should give {"chunky" => 3, "bacon" => 1, "fox" => 1}.def count_words(words)
counts = {}
# count each word
counts
end
count_words(%w[chunky bacon chunky fox chunky])Now with pins
PicoRuby was made for chips like the one on a Raspberry Pi Pico. Lesson 96 puts the Ruby of this lesson on a simulated Pico 2 W: an LED on a pin first, then buttons, sensors, a robot, an e-paper display, Wi-Fi and Bluetooth – with the same Task and sleep_ms as here.