Ruby
Basics
x = 10—Local variable
@x = 10—Instance variable
@@x = 10—Class variable
CONST = 10—Constant (uppercase)
$global = 10—Global variable
puts "text"—Print with newline
p obj—Inspect and print
"Hello #{name}"—String interpolation
:symbol—Symbol (immutable name)
Data Types & Methods
.class—Get object type
.nil?—Check if nil
.is_a?(Type)—Type check
.to_s / .to_i / .to_f—Type conversion
.freeze—Make immutable
.frozen?—Check if frozen
.dup / .clone—Copy object
.respond_to?(:method)—Check method exists
Strings
.length / .size—String length
.upcase / .downcase—Case conversion
.strip—Remove whitespace
.split(sep)—Split to array
.include?(sub)—Contains substring?
.gsub(pattern, replace)—Replace all matches
.start_with? / .end_with?—Prefix/suffix check
.chars / .bytes—Array of chars/bytes
.reverse—Reverse string
Arrays
arr = [1, 2, 3]—Create array
.push(x) / << x—Append element
.pop / .shift—Remove 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 / .compact—Flatten / remove nil
.sort / .sort_by—Sort elements
.uniq—Remove 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.values—All 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 / end—Conditional
unless cond—Negated if
puts "yes" if cond—Inline if
case val; when pat; end—Case statement
while / until—Loop types
n.times { |i| ... }—Loop n times
(1..10).each { |i| }—Range iteration
begin; rescue; end—Exception handling
Classes & Blocks
class MyClass; end—Define class
def initialize(a)—Constructor
attr_accessor :name—Getter + setter
attr_reader :name—Getter only
class B < A—Inheritance
module M; end—Module/mixin
include ModuleName—Include mixin
def method(&block)—Accept block
yield—Call the block
Proc.new { |x| x }—Proc object
-> (x) { x * 2 }—Lambda
allprintabledoc.com