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
yieldruns the caller's block from inside the method.- The block's value returns to the method like any expression.
block_given?makes the block optional instead of an error.
Keywords and builtins used here
defendifmaybe_logputstimedyield
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.
Step 2 of 3 in Methods & blocks, step 17 of 29 in Language basics.