← Back to Index

Ruby Reference

0. Basics

0.1 Hello World

# puts adds a newline; print does not
puts "Hello, World!"
TERMINAL OUTPUT
Hello, World!

0.2 Building & Running

Ruby is interpreted. Use the ruby command.

# Run a Ruby script
ruby main.rb
TERMINAL OUTPUT
Hello, World!

0.3 Comments

# Single-line comment

=begin
Multi-line comment block
(rarely used in practice)
=end
TERMINAL OUTPUT
(No output)

0.4 Imports

require 'json'           # Load from load path
require_relative 'local' # Load relative to current file
TERMINAL OUTPUT
(No output)

0.5 Exit Codes

# exit(status) - default is 0
exit(1)
TERMINAL OUTPUT
(Process exits with status 1)

0.6 Error Handling

begin
  1 / 0
rescue ZeroDivisionError => e
  puts "Caught: #{e.message}"
ensure
  puts "Cleanup"
end
TERMINAL OUTPUT
Caught: divided by 0
Cleanup

1. Environment & Time

1.1 Variable Declaration

x = 10          # Local variable
@x = 10         # Instance variable
@@x = 10        # Class variable
$x = 10         # Global variable
MAX_VAL = 100   # Constant (starts with uppercase)
TERMINAL OUTPUT
(No output)

1.2 Integer Types

Ruby integers have arbitrary precision (merged Fixnum/Bignum).

val = 2**128
puts val.class # Integer
TERMINAL OUTPUT
Integer

1.3 Casting

"123".to_i   # String to Integer
123.to_s     # Integer to String
"1.2".to_f   # String to Float
TERMINAL OUTPUT
(No output)

1.4 Truthiness

In Ruby, only false and nil are falsy. 0, "", and [] are all truthy.

puts "Zero is true" if 0
TERMINAL OUTPUT
Zero is true

1.5 Environment Vars

path = ENV['PATH']
ENV['MY_VAR'] = 'secret'
TERMINAL OUTPUT
(No output)

1.6 Time

require 'date'

now = Time.now
puts now.strftime("%Y-%m-%d %H:%M:%S")

# High-resolution monotonic clock
start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
TERMINAL OUTPUT
2024-05-16 12:00:00 (example)

2. Operators & Regex

2.1 Arithmetic/Logic

a = 10 / 3      # Integer division (3)
b = 10 / 3.0    # Float division (3.333...)
c = 10 ** 2     # Power (100)
d = true && false # Logic (also: and, or, not)
TERMINAL OUTPUT
(No output)

2.2 Regex

if "user@example.com" =~ /@/
  puts "Match found"
end

match = "price: $100".match(/\$(\d+)/)
puts match[1] if match
TERMINAL OUTPUT
Match found
100

3. Argument Parsing

3.1 CLI Argument Parsing

require 'optparse'

options = {}
OptionParser.new do |opts|
  opts.banner = "Usage: example.rb [options]"
  opts.on("-v", "--[no-]verbose", "Run verbosely") { |v| options[] = v }
end.parse!

# Remaining positional args are in ARGV
p ARGV
TERMINAL OUTPUT
[]

4. Functions & Memory

4.1 Declaration/Returns

def add(a, b = 0)
  return a + b # Explicit return
end

def multi
  [1, 2] # Implicit return (last expression)
end

x, y = multi # Unpacking
TERMINAL OUTPUT
(No output)

4.2 References/Pointers

Everything is an object passed by reference. Primitives are technically objects.

def modify(str)
  str << "!" # In-place modification
end

s = "hello"
modify(s)
puts s
TERMINAL OUTPUT
hello!

5. Loops & Iteration

5.1 Basic Loops

i = 0
while i < 3
  puts i
  i += 1
end

3.times { |j| puts j }
TERMINAL OUTPUT
0
1
2
0
1
2

5.2 Break/Continue

(0..5).each do |i|
  next if i == 1 # Equivalent to 'continue'
  break if i == 3
  puts i
end
TERMINAL OUTPUT
0
2

5.3 Iterating Collections

[10, 20].each { |v| puts v }

{1, 2}.each do |key, val|
  puts "#{key}: #{val}"
end
TERMINAL OUTPUT
10
20
a: 1
b: 2

6. Strings & Files

6.1 Manipulation

s = "  hello  "
s.strip!      # In-place whitespace removal
s.capitalize  # "Hello"
"a-b".split("-") # ["a", "b"]
TERMINAL OUTPUT
(No output)

6.2 Path Joining

path = File.join("usr", "local", "bin")
TERMINAL OUTPUT
(No output)

6.3 Streaming I/O

File.open("data.bin", "rb") do |f|
  while (chunk = f.read(4096))
    # Process binary chunk
  end
end
TERMINAL OUTPUT
(No output)

6.4 Read to Memory

content = File.read("file.txt")
lines = File.readlines("file.txt")
TERMINAL OUTPUT
(No output)

7. Binary & Bitwise

7.1 Allocation/Packing

# Pack: L (uint32 LE), d (double)
data = [42, 3.14].pack("Ld")
# Unpack
val, pi = data.unpack("Ld")
TERMINAL OUTPUT
(No output)

7.2 Bitwise Ops

a = 0b1010 & 0b1100 # AND (0b1000)
b = 0b1010 | 0b1100 # OR  (0b1110)
c = 1 << 3          # Shift (8)
TERMINAL OUTPUT
(No output)

7.3 Hex Conversion

"ff".hex      # 255
255.to_s(16)  # "ff"
sprintf("%02x", 255) # "ff"
TERMINAL OUTPUT
(No output)

8. Collections & JSON

8.1 Lists/Maps/Sets

require 'set'

arr = [1, 2, 3]
hash = { "key" => "value", 1 }
set = Set.new([1, 2, 2]) # {1, 2}
TERMINAL OUTPUT
(No output)

8.2 JSON Parsing

require 'json'

obj = JSON.parse('{"a": 1}')
json_str = JSON.generate(obj)
TERMINAL OUTPUT
(No output)

9. Systems & Networking

9.1 TCP

require 'socket'

# Client
begin
  s = TCPSocket.new('localhost', 80)
  s.puts "GET / HTTP/1.0\r\n\r\n"
  puts s.read
  s.close
rescue Errno::ECONNREFUSED
end
TERMINAL OUTPUT
(No output)

9.2 UDP

require 'socket'

u = UDPSocket.new
u.send("ping", 0, '127.0.0.1', 8080)
TERMINAL OUTPUT
(No output)

9.3 Concurrency

# Threads
t = Thread.new { puts "In thread" }
t.join

# Fibers (Lightweight)
f = Fiber.new { Fiber.yield "yielded" }
puts f.resume

# Ractors (Ruby 3 Parallelism - Experimental)
r = Ractor.new { "hello" }
puts r.take
TERMINAL OUTPUT
In thread
yielded
hello

9.4 SQLite

require 'sqlite3'

db = SQLite3::Database.new ":memory:"
db.execute "CREATE TABLE t(id INTEGER)"
db.execute "INSERT INTO t VALUES (42)"
puts db.get_first_value "SELECT id FROM t"
TERMINAL OUTPUT
42