Reading — step 1 of 6
Learn
~1 min readBlocks, Procs, Lambdas
A block is a chunk of code passed to a method. Two syntaxes:
# do/end — for multi-line or visual emphasis
[1, 2, 3].each do |n|
puts n * 2
end
# braces {} — for one-liners (idiomatic)
[1, 2, 3].each { |n| puts n * 2 }
Most iteration in Ruby uses blocks. The receiver method yields to the block:
def three_times
yield 1
yield 2
yield 3
end
three_times { |i| puts i } # 1, 2, 3
yield calls whatever block was passed. Use block_given? to check whether one was provided:
def maybe_log
yield "hi" if block_given?
end
Common block-taking methods:
[1, 2, 3].map { |n| n * 2 } # [2, 4, 6]
[1, 2, 3].select { |n| n > 1 } # [2, 3]
[1, 2, 3].reject { |n| n > 1 } # [1]
[1, 2, 3].reduce(0) { |s, n| s + n } # 6
[1, 2, 3].each_with_index { |n, i| puts "#{i}: #{n}" }
Most methods return the result of evaluating the block on each element — not just nil.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…