Ruby

Basics

x = 10Local variable
@x = 10Instance variable
@@x = 10Class variable
CONST = 10Constant (uppercase)
$global = 10Global variable
puts "text"Print with newline
p objInspect and print
"Hello #{name}"String interpolation
:symbolSymbol (immutable name)

Data Types & Methods

.classGet object type
.nil?Check if nil
.is_a?(Type)Type check
.to_s / .to_i / .to_fType conversion
.freezeMake immutable
.frozen?Check if frozen
.dup / .cloneCopy object
.respond_to?(:method)Check method exists

Strings

.length / .sizeString length
.upcase / .downcaseCase conversion
.stripRemove whitespace
.split(sep)Split to array
.include?(sub)Contains substring?
.gsub(pattern, replace)Replace all matches
.start_with? / .end_with?Prefix/suffix check
.chars / .bytesArray of chars/bytes
.reverseReverse string

Arrays

arr = [1, 2, 3]Create array
.push(x) / << xAppend element
.pop / .shiftRemove last / first
.map { |x| x * 2 }Transform each
.select { |x| x > 2 }Filter elements
.reject { |x| x < 2 }Reject matching
.reduce(0) { |sum, x| sum + x }Accumulate
.each { |x| puts x }Iterate
.flatten / .compactFlatten / remove nil
.sort / .sort_bySort elements
.uniqRemove duplicates
.first(n) / .last(n)First/last n elements

Hashes

h = { key: "val" }Create hash (symbol keys)
h[:key]Access value
h.fetch(:key, default)Safe access
h.keys / h.valuesAll keys / values
h.each { |k, v| ... }Iterate pairs
h.merge(other)Merge hashes
h.key?(:key)Key exists?
h.select { |k,v| cond }Filter hash

Control Flow

if / elsif / else / endConditional
unless condNegated if
puts "yes" if condInline if
case val; when pat; endCase statement
while / untilLoop types
n.times { |i| ... }Loop n times
(1..10).each { |i| }Range iteration
begin; rescue; endException handling

Classes & Blocks

class MyClass; endDefine class
def initialize(a)Constructor
attr_accessor :nameGetter + setter
attr_reader :nameGetter only
class B < AInheritance
module M; endModule/mixin
include ModuleNameInclude mixin
def method(&block)Accept block
yieldCall the block
Proc.new { |x| x }Proc object
-> (x) { x * 2 }Lambda
allprintabledoc.com