typestar

yield in Ruby

Methods that take a block and decide when to run it.

def timed
  start = Time.now
  result = yield
  puts "took #{(Time.now - start).round(4)}s"
  result
end

sum = timed { (1..100_000).sum }
puts sum

# block_given? makes the block optional
def maybe_log
  yield "saving" if block_given?
end

maybe_log { |msg| puts "log: #{msg}" }
maybe_log

How it works

  1. yield runs the caller's block from inside the method.
  2. The block's value returns to the method like any expression.
  3. block_given? makes the block optional instead of an error.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
279
Tokens
69
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 49 seconds.

Type this snippet

Step 2 of 3 in Methods & blocks, step 17 of 29 in Language basics.

← Previous Next →