Ruby Cheatsheet - Ruby Syntax & Methods Reference

Essential Ruby syntax for daily development, organized by category from basics to advanced features like blocks, modules, and metaprogramming. Copy directly when coding.

Languages·69 commands·Last updated 2026-07-21
Back to Languages

Basics 7

name = "Ruby"
Variable assignment, dynamic typing needs no declaration
name = "Hello, #{name}"
String interpolation, works in double quotes
:symbol
Symbol, immutable and unique, good as hash key
# single-line comment
Single-line comment starts with #
=begin comment block =end
Multi-line comment block
nil
Nil value, nil is also an object
true / false
Boolean value, also an object

Array & Hash 9

arr = [1, 2, 3]
Create an array
arr << 4
Append an element
arr[0]
Access element at index 0
arr.first / arr.last
First / last element
hash = { a: 1, b: 2 }
Create a hash (symbol-key shorthand)
hash[:a]
Access a hash value by key
hash[:c] = 3
Set a hash value by key
hash.key?(:a)
Check if a key exists
hash.keys / hash.values
Get all keys / values

Control Flow 10

if x > 0\n puts "positive"\nend
if conditional
puts "positive" if x > 0
Trailing if, concise form
unless x > 0\n puts "not positive"\nend
unless conditional, equivalent to if !
case x\nwhen 1 then "one"\nelse "other"\nend
case multi-branch match
3.times { puts "hi" }
Repeat a fixed number of times
1.upto(5) { |n| puts n }
Increment from 1 to 5
5.downto(1) { |n| puts n }
Decrement from 5 to 1
loop { break if done }
Infinite loop, needs manual break
while x > 0\n x -= 1\nend
while loop
until x == 0\n x -= 1\nend
until loop, equivalent to while !

Methods 9

def greet(name)\n "Hello, #{name}"\nend
Define a method, last line auto-returns
def greet(name = "World")
Method parameter with default value
def sum(*args)
splat operator, accepts variable args
def method(a:, b:)
Keyword arguments, order-independent
return value
Explicit return value (optional)
def method\n yield if block_given?\nend
yield invokes the passed block
my_proc = Proc.new { |x| x*2 }
Create a Proc object
my_lambda = ->(x) { x*2 }
Create a Lambda (arrow syntax)
proc.call(5)
Call a Proc / Lambda

Class & Module 10

class MyClass\nend
Define a class
attr_accessor :name
Auto-generate getter and setter
attr_reader :name
Read-only getter
attr_writer :name
Write-only setter
class Child < Parent
Class inheritance
module MyModule\nend
Define a module
include MyModule
Mixin module methods (instance methods)
extend MyModule
Mixin module methods (class methods)
self.class_method
self refers to current object, define class method
class << self\nend
Singleton class, define class methods

Exception 7

begin\n risky_call\nrescue\n "error"\nend
begin-rescue catches exceptions
rescue SpecificError => e
Catch a specific exception type
ensure\n cleanup\nend
ensure guarantees cleanup runs
raise "error message"
Manually raise an exception
raise ArgumentError, "msg"
Raise a specific exception type
retry
retry inside rescue repeats the begin block
catch(:done) { throw(:done) }
catch/throw non-local jump

Built-in Methods 10

arr.map { |x| x*2 }
Array#map transforms an array
arr.select { |x| x.even? }
Array#select filters evens
arr.reject { |x| x.even? }
Array#reject excludes evens
arr.reduce(0) { |s, x| s + x }
Array#reduce sums
hash.merge({ c: 3 })
Hash#merge merges hashes
"hello".upcase
String#upcase uppercases
"hello".split("")
String#split splits a string
"hello".gsub(/l/, "L")
String#gsub global replace
arr.flatten
Array#flatten flattens nested arrays
arr.uniq
Array#uniq deduplicates

Blocks & Iterators 7

[1, 2].each { |n| puts n }
each iterates over elements
[1, 2].each do |n|\n puts n\nend
do...end block, equivalent to {}
(1..5).map { |n| n**2 }
map transforms (returns new array)
[1, 2, 3].select(&:even?)
select with &: shorthand
arr.partition { |x| x.even? }
partition into two groups [[evens], [odds]]
arr.chunk { |x| x > 0 }
chunk groups by condition
arr.group_by { |x| x % 3 }
group_by groups into a hash by condition

Tips

  • Everything in Ruby is an object, including nil and numbers.
  • each is the most common iterator; map transforms, select filters.
  • Symbol :symbol is immutable and unique, good as a hash key.
  • attr_accessor auto-generates getter and setter.
  • Blocks are Ruby's most powerful feature; do...end and {} are equivalent.

Official References

Commands are compiled from the official docs below. Click to verify the latest usage.

Maintained by LaoHand

Publicly updated on Jul 21, 2026, continuously proofread against official docs.

Contact Us

Wrong command or description? Send us corrections, business inquiries or product feedback by email.

Contact Us