Ruby Cheatsheet
Ruby is an expressive, object-oriented language known for developer happiness and the Rails web framework.
Everything is an object. Learn blocks and Enumerable early—they power most everyday Ruby code.
Full lessons: Ruby Tutorials
Basics
Hello
Print with puts. Run a file with ruby app.rb.
puts "Hello"
Variables
Snake_case locals. Constants start with an uppercase letter.
name = "Ada"
MAX = 100
Symbols
Lightweight immutable labels, often used as hash keys.
status = :ok
user = { name: "Ada", id: 1 }
String interpolation
Double-quoted strings interpolate with #{...}.
puts "Hi, #{name}"
irb / pry
Interactive shells for trying snippets.
irb
Arrays, hashes, Enumerable
Arrays
Ordered lists with rich methods.
nums = [1, 2, 3]
nums << 4
Hashes
Key/value maps. Prefer symbol keys in new code.
book = { title: "Practical Ruby", year: 2024 }
book[:title]
map / select
Transform and filter with Enumerable.
nums.map { |n| n * 2 }
nums.select { |n| n.even? }
each
Iterate with a block.
nums.each do |n|
puts n
end
Methods & classes
Method
Define with def. Last expression is the return value.
def add(a, b)
a + b
end
Keyword args
Name parameters for clarity.
def greet(name: "friend")
"Hi, #{name}"
end
Class
Instance variables use @. Expose with attr_reader / attr_accessor.
class User
attr_reader :name
def initialize(name)
@name = name
end
end
Modules
Namespaces and mixins shared across classes.
module Greetable
def greet
"Hi"
end
end
Errors & gems
begin / rescue
Handle exceptions; rescue specific classes when possible.
begin
File.read("missing.txt")
rescue Errno::ENOENT => e
warn e.message
end
raise
Raise an error with a message or exception class.
raise ArgumentError, "name required"
Gemfile
Bundler manages gem dependencies.
bundle init
bundle add sinatra
bundle install
require
Load a gem or file.
require "json"
JSON.parse('{"a":1}')
Comments
One comment per signed-in account. Comments are saved with this page’s URL.