A loose collection of Ruby fun facts and examples to organize your code in a single file.
Let’s have some fun with Ruby!
There is $0.
Contains the name of the file containing the Ruby script being executed.
Source: Pre-defined variables and constants
def greet(name)
"Hello #{name}!"
end
# this will only run if the script was the main
# not load'd or require'd
if __FILE__ == $0
require "test/unit/assertions"
include Test::Unit::Assertions
assert_equal 'Hello Ruby', greet('Ruby'), "greet function should return 'Hello Ruby!'"
end$ ruby code_and_test.rb
greet function should return 'Hello Ruby!'. (Test::Unit::AssertionFailedError)
<"Hello Ruby"> expected but was
<"Hello Ruby!">.
diff:
- Hello Ruby
+ Hello Ruby!
?require './code_and_test.rb'
puts greet "Christian"$ ruby code_and_test_usage.rb
Hello Christian!def hello():
print("Hello world, this script was called!")
if __name__ == '__main__':
hello()Source: Python Define Unit Test Classes Together with Code
Before Ruby, my favorite web framework was CodeIgniter.
Security first: One index.html file in EVERY folder.
sudo gem install sinatrarequire "rubygems"
require "sinatra"
get '/' do
"Hello World"
endAwesome!!!
ruby myapp.rb“You can do this too but it’s not as cool” - Sinatra Readme
template :index do
'%div.title Hello World!'
endAs documented in the README.rdoc this was the cool way to do it.
get '/' do
haml :index
end
use_in_file_templates!
__END__
@@ layout
X
= yield
X
@@ index
%div.title Hello world!!!!!Why the name ‘Ruby’?
Influenced by Perl, Matz wanted to use a jewel name for his new language, so he named Ruby after a colleague’s birthstone.
Source: The Ruby Language FAQ
Ruby took a lot of things from Pearl.
Today we will learn about:
- Keywords
- Command line flags
Perl has two special literals:
__END__- Indicates the logical end of the script before the actual end of file. Any following text is ignored.__DATA__- A filehandle that points to everything that comes after__END__.
Source: perldata - perldoc.perl.org
Denotes the end of the regular source code section of a program file. Lines below
__END__will not be executed.
Those lines will be available via the special filehandle
DATA
Source: Class: Object
DATA.each_line do |line|
puts line
end
__END__
Cats
Dogs
Micerequire 'erb'
time = Time.now
renderer = ERB.new(DATA.read)
puts renderer.result()
__END__
The current time is <%= time %>.get '/' do
haml :index
end
use_in_file_templates!
__END__
@@ layout
X
= yield
X
@@ index
%div.title Hello world!!!!!File.read(caller.first.split(":").first).split("__END__", 2).lastSource: Mixing code and data in Ruby
// open self
$fp = fopen(__FILE__, 'rb');
// seek file pointer to data
//__COMPILER_HALT_OFFSET__ will return
//the point after __halt_compiler();
fseek($fp, __COMPILER_HALT_OFFSET__);
// and output it
$unpacked = gzinflate(stream_get_contents($fp));
__halt_compiler();
//now here... all the binary gzdeflate already items!!!Source: PHP: __halt_compiler - Manual Example: __halt_compiler(), make install files for PHP smaller
Fun fact: You don’t need a Gemfile to use bundler!
Useful for scripts in your /utils folder that you only use once a year.
Source: How to use Bundler in a single-file Ruby script
require 'bundler/inline'
gemfile do
gem 'httparty'
end
puts HTTParty.get('https://www.boredapi.com/api/activity')require 'bundler/inline'
gemfile do
gem 'minitest', require: false
end
require 'minitest/autorun'
class MyTest < Minitest::Test
def test_should_be_true
assert_equal true, true
end
end- Install Dependencies
- Do stuff (download calendar events)
- Render to ERb template
Source: ical_to_org.rb
Yes, this is taken from Perl as well.
BEGIN defines a block that is run before any other code in the current file. It is typically used in one-liners with ruby -e.
Similarly END defines a block that is run after any other code.
Source: Documentation for Ruby 2.2.0
END { puts 3 }
BEGIN { puts 1 }
puts 2ruby begin.rb
1
2
3Logging Ruby - The Ruby alias for the forgetful scripter Logging Ruby!
Only Feature: No more scrolling through your terminal… Logs the output of a script to the script itself!
cat log_results/hello_world.rbruby log_results/hello_world.rblruby log_results/hello_world.rbcat log_results/hello_world.rbwhich lrubyLet’s check out the source of LRuby lruby.rb
Aaaaand back to Perl!
perl -xLeading garbage will be discarded until the first line that starts with #! and contains the string “perl”.
Source: perlrun - perldoc.perl.org
Tells Perl that the program is embedded in a larger chunk of unrelated text, such as in a mail message.
ruby -xTells Ruby that the script is embedded in a message. Leading garbage will be discarded until the first that starts with “#!” and contains string “ruby”.
Source: Ruby Docs Command line Options
Hello dear friend,
this is a mail message. Please execute it with your ruby interpreter.
Thanks,
a random stranger
#! hahaha this is ruby now
puts "Hello World"ruby -x email.emlThis is not an animated gif, but a gif that animates itself.
The trailer block indicates when you’ve reached the end of the file. It is always a byte with a value of 3B.
Source: What’s In A GIF
- GIFs are nice
- GIFs always end with the same terminator byte
- Ruby is nice
- Ruby can start with a defined start line
- Nice.
This is not an animated gif, but a gif that animates itself.
- One file
- Upper half is a GIF
- Lower half is Ruby code
- File rewrites itself!
- Profit!
Let’s check out the together!
while 1; do cd /users/fabrik42/desktop/single-file-ruby-programs/rbgif; time ruby -x ./rbgif.gif; sleep 0.1; done#!/bin/sh
echo This is bash
i=12
echo $i
perl - $i <<'__HERE__'
my $i = shift;
print "This is perl\n";
print ++$i . "\n";
__HERE__
echo This is bash again
echo $iSource: perl script inside a shell script
- “Ain’t that fun?” - dchetlin
- “It’s strange and terrible and I’m not sure how to get something out of the perl part, but this sort of works” - eg
- “This, on the other hand is just … just .. well, I don’t know. Not right. Not even wrong. It just is.” - Blue
- Code & Tests
- Dependencies & Code
- Data & Code
- Code & Data
- Code & Output
Try it out for fun and profit!
Questions?
Christian Bäuerlein @fabrik42
- Single file Rails applications (for fun and bug reporting) | Christoph Lupprich
- Putting Ruby on Rails on a diet
- basics/inline-activerecord.rb at 884229e117a13f0bcbdc8aa34047905726713527
- teamon/minirails: Smallest Rails (and other) Apps
- The Smallest Rails App
- artemave/thesmallestrailsapp.com
- Dissecting thesmallestrailsapp.com (Smallest Rails App: line 3) · Tweetegy
- How to create an inline / minimal Rails app? - Stack Overflow
- Guestbook
- Thor command line tools
- Advent of Code template using
__DATA__for input - HTML docs and code in one file?
- Awesome ascii art readme
- Actually, BEGIN/END is taken from AWK: AWK-ward Ruby
- duct is a predecessor of
bundler/inlineporras/duct: Duct allows you to embed a Gemfile in a single file script - Pre-defined variables and constants
- keywords - Documentation for Ruby 2.2.0
- Idiosyncratic Ruby: Constant Shadows
- Idiosyncratic Ruby: Literate Ruby
- perl -x to test while developing
- A Single file Rails Application | Greg Molnar
- Single File Rails Apps · Fly


