Jupyter Notebooks with Ruby
This post documents how to set up Jupyter notebooks with Ruby support and embed them in blog posts.
Pre-conditions
gem install iruby
iruby register --force
brew install jupyter
Later, you can check the installed versions of IRuby with:
for version in $(rbenv versions --bare); do echo "=== Ruby $version ===" && RBENV_VERSION=$version gem list iruby 2>/dev/null | grep -E "^iruby" || echo "iruby not installed"; done
Local usage:
jupyter lab
Webbrowser usage: http://localhost:8888/lab
Workflow
-
Create your notebook (
.ipynbfile) - either via Jupyter Lab or by writing the JSON directly -
Convert to HTML:
/opt/homebrew/opt/jupyterlab/bin/jupyter nbconvert --to html notebooks/your-notebook.ipynb
-
Extract the
<main>content from the generated HTML -
Add the Jupyter CSS to your site’s stylesheet (see
assets/css/codeblock.css) -
Embed the HTML directly in your blog post
Example
stdout
puts writes to stdout:
In [1]:
puts "This is stdout"
This is stdout
stderr
Two ways to write to stderr:
In [2]:
warn "Using warn"
Using warn
In [3]:
$stderr.puts "Using $stderr.puts"
Using $stderr.puts
Return value
The last expression's value shows with Out label:
In [4]:
"This is a return value"
Out[4]:
"This is a return value"
All three together
Output order: stdout, stderr, then return value:
In [5]:
puts "1. stdout via puts"
warn "2. stderr via warn"
$stderr.puts "3. stderr via $stderr.puts"
"4. return value"
1. stdout via puts
2. stderr via warn 3. stderr via $stderr.puts
Out[5]:
"4. return value"