Ruby Cheatsheet
Enumerable and Blocks
Use this Ruby reference while you build software engineering projects, review code, or refresh the syntax you reach for most.
Blocks
Blocks pass behavior into methods.
[1, 2, 3].each { |n| puts n } [1, 2, 3].each do |n| puts n end
Use braces for short single-line blocks and do ... end for multi-line blocks.
Core Enumerable Methods
items.each { |x| puts x } # side effects
items.map { |x| transform(x) } # array of transformed values
items.flat_map { |x| x.children } # map then flatten one level
items.select { |x| keep?(x) } # matching items
items.reject { |x| skip?(x) } # non-matching items
items.find { |x| wanted?(x) } # first match or nil
items.any? { |x| x.valid? }
items.all? { |x| x.valid? }
items.none?(&:nil?)
items.count { |x| x.active? }reduce / inject
[1, 2, 3].reduce(0) { |sum, n| sum + n } # 6 [1, 2, 3].inject(:+) # 6 words.reduce({}) do |hash, word| hash[word] = word.length hash end
For hashes and arrays, each_with_object is often clearer than reduce because you do not need to return the accumulator each time.
each_with_object
words = ["ruby", "rails", "ruby"] counts = words.each_with_object(Hash.new(0)) do |word, hash| hash[word] += 1 end
Short Symbol-to-Proc Form
names.map(&:downcase) # names.map { |name| name.downcase } nums.select(&:even?) users.map(&:email)
Use &:method_name only when you call one method with no extra arguments. Use a normal block for anything more complex.
yield
def around(label) puts "before #{label}" result = yield puts "after #{label}" result end around("work") { 2 + 2 }
Explicit Blocks
def measure(&block) start = Time.now result = block.call [result, Time.now - start] end
&block converts the passed block into a Proc object. This is useful when you need to store, forward, or call the block more than once.
Procs and Lambdas
square = proc { |n| n * n } square.call(5) # 25 strict = ->(n) { n * n } strict.call(5)
Lambdas check argument count more strictly and return behaves like returning from the lambda. Plain procs are looser and can surprise beginners inside methods.