Menu

Ruby Cheat Sheet

Last updated

Hello World & running code

Ruby needs no boilerplate - a single line runs.

OperationSyntax
Print with newlineputs "Hello, World!"
Print without newlineprint "Hello"
Inspect a valuep [1, 2, 3]
String interpolationputs "Hi #{name}"
Comment# this is a comment
Multi-line comment=begin ... =end
Run a fileruby app.rb
Interactive shellirb

Variables & types

Ruby is dynamically typed; everything is an object.

OperationSyntax
Local variableage = 30
ConstantPI = 3.14
Instance variable@name = "Ada"
Global variable$count = 0
Symbol:status
Nil / booleannil, true, false
Check type42.class returns Integer
Convert type"42".to_i, 42.to_s, "3.5".to_f

Strings

Strings are mutable objects with a rich method set.

OperationSyntax
Length"hello".length
Upper / lower cases.upcase, s.downcase
Trim whitespaces.strip
Replaces.gsub("a", "b")
Split into array"a,b,c".split(",")
Includes substrings.include?("ell")
Slice characterss[0..2]
Concatenate"foo" + "bar", s << "!"
Repeat"ab" * 3
Formatformat("%05d", 42)

Arrays

Ordered, integer-indexed collections.

OperationSyntax
Createnums = [1, 2, 3]
Access by indexnums[0], nums[-1]
Add to endnums.push(4), nums << 4
Remove from endnums.pop
Lengthnums.length
Mapnums.map { |n| n * 2 }
Filternums.select { |n| n.even? }
Reducenums.reduce(0) { |sum, n| sum + n }
Sortnums.sort
Join to stringnums.join(", ")

Hashes

Key-value collections, often keyed by symbols.

OperationSyntax
Createuser = { name: "Ada", age: 30 }
Access valueuser[:name]
Set valueuser[:email] = "a@x.com"
Check keyuser.key?(:name)
Delete keyuser.delete(:age)
Keys / valuesuser.keys, user.values
Iterateuser.each { |k, v| puts "#{k}: #{v}" }
Default valueHash.new(0)
Mergeh1.merge(h2)

Control flow

Conditionals and loops; note Ruby's trailing modifiers.

OperationSyntax
If / elsif / elseif x > 0 ... elsif x < 0 ... else ... end
Inline if (modifier)puts "hi" if ready
Unlessunless done ... end
Ternaryx > 0 ? "pos" : "neg"
Case / whencase n; when 1 then ...; else ...; end
While loopwhile i < 10 ... end
Until loopuntil done ... end
Times5.times { |i| puts i }
Range iteration(1..5).each { |i| puts i }
Break / nextbreak, next

Methods

The last expression is returned implicitly.

OperationSyntax
Define a methoddef add(a, b) ... end
Implicit returndef square(x) x * x end
Default argumentdef greet(name = "World") ... end
Keyword argumentsdef box(w:, h:) ... end
Splat (variadic)def sum(*nums) ... end
Method ending in ?def valid? ... end
Method ending in !def normalize! ... end
Call with no parensgreet "Ada"

Blocks, procs & lambdas

Blocks are chunks of code passed to methods; procs and lambdas store them.

OperationSyntax
Block (braces)[1, 2].each { |n| puts n }
Block (do/end)[1, 2].each do |n| puts n end
Yield to a blockdef run; yield; end
Block given checkblock_given?
Capture block as paramdef run(&blk); blk.call; end
Create a procsquare = proc { |x| x * x }
Create a lambdasquare = ->(x) { x * x }
Call a proc / lambdasquare.call(3), square.(3)

Classes & modules

Classes hold state and behavior; modules mix in shared methods.

OperationSyntax
Define a classclass Point ... end
Constructordef initialize(x, y) @x = x; @y = y; end
Instance methoddef dist ... end
Accessor shortcutsattr_accessor :x, :y
Create instancep = Point.new(1, 2)
Inheritclass Circle < Shape ... end
Class methoddef self.origin ... end
Define a modulemodule Drawable ... end
Mix in a moduleinclude Drawable
Call supersuper(args)

The Ruby syntax you reach for most, on one page. This Ruby cheat sheet is a quick reference for the core language - variables and types, strings, arrays and hashes, control flow, methods, and the blocks, procs, and lambdas that make Ruby so expressive.

Everything here is plain Ruby and runs on any standard interpreter. Copy what you need, or try every snippet live in the Ruby playground - no install required.

Ruby cheat sheet FAQ

Is this Ruby cheat sheet free?
Yes. This Ruby cheat sheet is completely free, with no sign-up required. Bookmark it and come back whenever you need to look up a string method, hash operation, or block syntax.
What is the difference between a block, a proc, and a lambda?
A block is an anonymous chunk of code passed to a method with { ... } or do ... end - it is not an object on its own. A proc wraps a block in a callable object you can store and pass around. A lambda is a special proc that checks its argument count strictly and treats return as returning from the lambda itself, whereas a plain proc returns from the enclosing method.
What are symbols in Ruby?
A symbol like :name is an immutable, reusable identifier. Because the same symbol always points to the same object in memory, symbols are faster and more memory-efficient than strings for things like hash keys and method names - which is why you often see hashes written as { name: "Ada" }.
Can I practice Ruby online?
Yes. Open the Ruby playground to run any snippet from this cheat sheet in your browser - no Ruby install needed. When you want structure, Coddy's free interactive Ruby course takes you from variables and strings to blocks and classes step by step.
Is this cheat sheet good for beginners?
Yes. It is organized from the most common topics (variables, strings, control flow) down to advanced ones (blocks, procs, classes), so you can use the top sections on day one and grow into the rest.
Coddy programming languages illustration

Learn Ruby with Coddy

GET STARTED