Arrays
Ruby arrays are dynamic, heterogeneous, and ridiculously powerful via Enumerable. .map, .select, .reduce, .zip — you’ll reach for them every five lines.
Build, transform, slice
EXAMPLE
# Build
xs = [1, 2, 3, 4]
ys = Array.new(5, 0) # [0, 0, 0, 0, 0]
zs = Array.new(3) { |i| i * i } # [0, 1, 4]
ws = %w[red green blue] # %w skips quotes & commas
# Index + slice
xs[0] # 1
xs[-1] # 4 (negative wraps)
xs[1..2] # [2, 3] inclusive
xs[1...3] # [2, 3] exclusive end
xs.first(2) # [1, 2]
xs.last # 4
xs.take(2)
xs.drop(2)
# Mutators
xs << 5
xs.push(6)
xs.unshift(0)
xs.pop # 6
xs.shift # 0
xs.insert(1, 99)
xs.delete_at(0)
# Enumerable — the bread and butter
xs.map { |n| n * n }
xs.select { |n| n.even? }
xs.reject { |n| n.even? }
xs.reduce(:+) # sum
xs.sum
xs.min; xs.max; xs.minmax
xs.each_with_index { |n, i| puts "#{i}: #{n}" }
xs.group_by { |n| n % 3 }
xs.partition(&:even?) # [[evens], [odds]]
xs.uniq
xs.sort_by { |n| -n }
# Multi-array
[1, 2, 3].zip([:a, :b, :c]) # [[1,:a],[2,:b],[3,:c]]
[[1, 2], [3, 4]].flatten # [1, 2, 3, 4]
# Destructuring
first, *rest = [10, 20, 30, 40] # first=10, rest=[20,30,40]
Why it matters
Enumerable is in your blood after a few weeks of Ruby. The same method names show up on Hash, Range, custom classes — learn the verbs once, use them everywhere.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…