Reading — step 1 of 5
Learn
~1 min readMethods and Blocks
Methods can take a block and yield to it — the magic that powers Ruby's iterators.
def twice
yield
yield
end
twice { puts "hi" } # prints 'hi' twice
yield passes args to the block and returns the block's value:
def times_two
yield 5
end
result = times_two { |n| n * 2 } # 10
For named, reusable blocks, use Proc or Lambda:
double = ->(n) { n * 2 } # lambda — strict on arity
double.call(5) # 10
double.(5) # also works
Lambdas check argument count and return returns from the lambda. Procs are lenient and return returns from the enclosing method. For new code, prefer lambdas (stricter, less surprising).
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…