RB

Ruby Cheatsheet

Core Ruby syntax - blocks, enumerables, and the concise conventions Ruby is known for.

Basics

x = 5

Variable assignment

def add(a, b) a + b end

Method declaration

arr = [1, 2, 3]

Array literal

hash = { key: "value" }

Hash (symbol keys)

"#{name} is here"

String interpolation

Enumerables & blocks

arr.map { |x| x * 2 }

Transform each element

arr.select { |x| x > 0 }

Filter elements

arr.each { |x| puts x }

Iterate without transforming

arr.reduce(0) { |sum, x| sum + x }

Reduce to a single value

Control flow

if x > 0 ... end

If statement

x > 0 ? "yes" : "no"

Ternary expression

puts "hi" if x > 0

Trailing conditional

3.times { puts "hi" }

Repeat a block n times