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.
Back to LanguagesBasics 7
name = "Ruby"Variable assignment, dynamic typing needs no declaration
name = "Hello, #{name}"String interpolation, works in double quotes
:symbolSymbol, immutable and unique, good as hash key
# single-line commentSingle-line comment starts with #
=begin
comment block
=endMulti-line comment block
nilNil value, nil is also an object
true / falseBoolean value, also an object
Array & Hash 9
arr = [1, 2, 3]Create an array
arr << 4Append an element
arr[0]Access element at index 0
arr.first / arr.lastFirst / last element
hash = { a: 1, b: 2 }Create a hash (symbol-key shorthand)
hash[:a]Access a hash value by key
hash[:c] = 3Set a hash value by key
hash.key?(:a)Check if a key exists
hash.keys / hash.valuesGet all keys / values
Control Flow 10
if x > 0\n puts "positive"\nendif conditional
puts "positive" if x > 0Trailing if, concise form
unless x > 0\n puts "not positive"\nendunless conditional, equivalent to if !
case x\nwhen 1 then "one"\nelse "other"\nendcase 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\nendwhile loop
until x == 0\n x -= 1\nenduntil loop, equivalent to while !
Methods 9
def greet(name)\n "Hello, #{name}"\nendDefine 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 valueExplicit return value (optional)
def method\n yield if block_given?\nendyield 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\nendDefine a class
attr_accessor :nameAuto-generate getter and setter
attr_reader :nameRead-only getter
attr_writer :nameWrite-only setter
class Child < ParentClass inheritance
module MyModule\nendDefine a module
include MyModuleMixin module methods (instance methods)
extend MyModuleMixin module methods (class methods)
self.class_methodself refers to current object, define class method
class << self\nendSingleton class, define class methods
Exception 7
begin\n risky_call\nrescue\n "error"\nendbegin-rescue catches exceptions
rescue SpecificError => eCatch a specific exception type
ensure\n cleanup\nendensure guarantees cleanup runs
raise "error message"Manually raise an exception
raise ArgumentError, "msg"Raise a specific exception type
retryretry 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".upcaseString#upcase uppercases
"hello".split("")String#split splits a string
"hello".gsub(/l/, "L")String#gsub global replace
arr.flattenArray#flatten flattens nested arrays
arr.uniqArray#uniq deduplicates
Blocks & Iterators 7
[1, 2].each { |n| puts n }each iterates over elements
[1, 2].each do |n|\n puts n\nenddo...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