TIL: Single file Ruby scripts
in Ruby
Running some Python scripts with uv, I came across its support for declaring script dependencies in the Python file itself:
# /// script
# dependencies = [
# "requests<3",
# "rich",
# ]
# ///
import requests
from rich.pretty import pprint
resp = requests.get("https://peps.python.org/api/peps.json")
data = resp.json()
pprint([(k, v["title"]) for k, v in data.items()][:10])
I figured something like this should be possible in Ruby. And indeed it is!
As long as you have Bundler, you can write self-contained Ruby scripts - with dependencies - using bundler/inline
.
My favourite use is quick scrapers with Nokogiri:
require 'bundler/inline'
require 'open-uri'
gemfile do
source 'https://rubygems.org'
gem 'nokogiri'
end
doc = Nokogiri::HTML(URI.open('https://czak.pl/til/single-file-ruby-scripts'))
puts doc.title