Ruby Language Cheat Sheet
A searchable reference of core Ruby syntax and what each snippet does.
| Snippet | What it does |
|---|---|
puts "hello" | Print a value followed by a newline to standard output. |
p [1, 2, 3] | Print a value using inspect, showing quotes and structure, then return it. |
name = "Ada" | Assign a value to a local variable; no declaration keyword is needed. |
"Hi #{name}" | Embed a Ruby expression inside a double-quoted string. |
:status | A lightweight immutable name often used as a hash key. |
x = nil | The single object that represents no value, similar to null. |
MAX = 100 | A name starting with a capital letter; reassigning it warns. |
# a comment | Text after a hash mark on a line is ignored by Ruby. |
require "json" | Load a standard library or gem so its code becomes available. |
nums = [1, 2, 3] | Create an ordered, index-based list of values. |
nums.push(4) | Append an element to the end of an array; the << operator does the same. |
nums.each { |n| puts n } | Run the block once for every element in the collection. |
nums.map { |n| n * 2 } | Build a new array from the block return value for each element. |
nums.select { |n| n > 1 } | Keep only the elements for which the block returns true. |
nums.reject { |n| n > 1 } | Drop the elements for which the block returns true. |
nums.reduce(0) { |sum, n| sum + n } | Combine every element into one value using an accumulator. |
h = { a: 1, b: 2 } | Create a collection of key and value pairs, like a dictionary. |
h.each { |k, v| puts k } | Iterate a hash, passing each key and value to the block. |
h.keys | Return an array of the hash keys; use values for the values. |
(1..5).to_a | Two dots include the end value; three dots exclude it. |
"hello".length | Return the number of characters in a string. |
"Hi".upcase | Return an uppercase copy; use downcase for lowercase. |
"a,b,c".split(",") | Break a string into an array on a separator. |
["a", "b"].join("-") | Join array elements into one string with a separator between them. |
"foo".gsub("o", "0") | Replace every match of a pattern with a replacement string. |
" hi ".strip | Remove leading and trailing whitespace from a string. |
"hello".include?("ell") | Return true when the string contains the given substring. |
42.to_s | Convert a value to a string; use to_i to parse an integer. |
"abc".chars | Return an array of the individual characters in a string. |
if a; x; elsif b; y; else; z; end | Run the first branch whose condition is true; end closes it. |
save unless invalid | Run the code only when the condition is false, the opposite of if. |
case x; when 1 then "one"; else "other"; end | Compare one value against several when clauses. |
while i < 10; i += 1; end | Repeat the body while the condition stays true. |
until done; work; end | Repeat the body until the condition becomes true. |
for i in 1..3; puts i; end | Iterate over a range or collection; each is more idiomatic. |
x > 0 ? "pos" : "neg" | A compact if-else that returns one of two values. |
a && b || c | Combine booleans; && and || bind tighter than the words and and or. |
def greet; "hi"; end | Define a method; the value of the last expression is returned. |
return x if x > 0 | Exit a method early and hand back a value. |
def greet(name = "world"); end | Give a parameter a fallback used when no argument is passed. |
def area(w:, h:); w * h; end | Name arguments at the call site, as in area(w: 2, h: 3). |
def sum(*nums); nums.sum; end | Gather any number of positional arguments into an array. |
def run; yield; end | Run the block passed to a method using the yield keyword. |
square = ->(x) { x * x } | Create a callable lambda; invoke it later with call. |
class Dog; end | Define a class, a blueprint used to build objects. |
def initialize(name); @name = name; end | The constructor method that runs when you call new. |
attr_accessor :name | Generate a getter and a setter for an instance variable. |
class Cat < Animal; end | Make a class inherit behavior from a parent using the < sign. |
module Greet; end | Define a namespace or a set of methods to mix in. |
class Dog; include Greet; end | Mix the instance methods of a module into a class. |
def self.create; end | Define a class method; self refers to the current object or class. |
private | Mark the methods below as callable only from inside the object. |
obj.respond_to?(:save) | Return true when the object has a method with that name. |
No snippets match your search.
Runs entirely in your browser. Nothing you type is sent anywhere; open DevTools and watch the Network tab to verify zero requests.
What this tool does
This is a searchable quick reference for the Ruby syntax you use every day, from printing and variables to arrays, hashes, strings, control flow, methods, and the object-oriented building blocks. Each row pairs a small snippet with a plain-English note on what it does. Type in the filter box to search across both columns, or tap a category button to focus on one area. The whole list is built into the page, so it works offline and sends nothing anywhere.
How to use it
Start typing in the Filter box. Entering map jumps to
the array transform methods; entering gsub surfaces string replacement;
entering class shows the object-oriented basics. The
category buttons (Basics, Collections, Strings, Control flow, Methods,
OOP) narrow the table to one area and combine with the text filter, so you can pick
Collections and type each to see just the iteration helpers. Clear the box
to see the full sheet again.
Common use cases
- Recalling the exact form of a method you use rarely, like
reduceorattr_accessor. - Copying correct syntax into your editor instead of guessing.
- Teaching a newcomer the difference between
putsandp, or a block and a lambda. - Refreshing the core Ruby workflow before an interview or a new job.
- Looking up how symbols, hashes, and ranges are written.
Common pitfalls
- Single-quoted strings do not interpolate. Only double-quoted strings expand an embedded expression; a single-quoted string prints the placeholder text literally instead of the value.
- Confusing symbols and strings. A symbol such as
:nameis not the same object as the string of those letters, which matters when comparing values or looking up hash keys. - Truthiness surprises. Only
nilandfalseare falsy in Ruby, so the number 0 and an empty string are both truthy, unlike some other languages. - Mutating while iterating. Changing an array inside
eachormapcan skip elements or raise errors; build a new collection withmaporselectinstead.
Frequently asked questions
- What is a symbol in Ruby?
- A symbol is a lightweight, immutable name written with a leading colon, such as :name. Because each symbol exists only once in memory, symbols are faster to compare than strings and are the usual choice for hash keys, method names, and other fixed identifiers. Unlike a string, a symbol cannot be changed after it is created.
- What is the difference between a block, a proc, and a lambda?
- A block is an anonymous chunk of code passed to a method, written with do and end or with curly braces; it is not an object on its own. A proc is a block captured as an object, so you can store it in a variable and call it later. A lambda is a special kind of proc that checks its argument count strictly and returns only from itself, whereas a plain proc is lenient about arguments and a return inside it exits the surrounding method.
- What does attr_accessor do?
- attr_accessor is a shortcut that defines both a getter and a setter method for an instance variable of the same name. Writing attr_accessor :age creates an age method that reads @age and an age= method that assigns it, so you do not have to write those two methods by hand. Use attr_reader for a getter only, or attr_writer for a setter only.
- What is the difference between puts and p?
- puts prints a human-friendly version of a value and adds a trailing newline, calling to_s on the object and returning nil. p prints the developer-friendly inspect form, which shows quotes around strings and the structure of arrays and hashes, and it returns the value itself. Reach for puts in normal output and p when debugging.
- What is a mixin in Ruby?
- A mixin is a module whose methods are shared into a class with the include keyword, giving Ruby a clean way to reuse behavior without multiple inheritance. Because a class can include many modules, mixins let unrelated classes gain the same abilities, which is how core modules such as Enumerable and Comparable add their methods. The module holds the methods and each including class gains them as instance methods.
- Does this cheat sheet send anything to a server?
- No. The entire cheat sheet is baked into the page at build time and every search or filter runs locally in your browser with JavaScript, so nothing you type leaves your device. Open your browser DevTools and watch the Network tab while you use it to confirm there are zero requests.
Cite this tool
For academic, journalistic, or technical references. Pick a format:
Citations use 2026 as the publication year. Access date is left as a fillable placeholder where the citation style expects one.