Methods that take a block: yield
Since lesson 6 you've been handing blocks to methods: 3.times { … }, each, map, select. Now you switch sides and write a method that receives a block yourself. The magic word is yield – as in “hand over”: at this spot, Ruby runs the block that came with the call. Two yields, the block twice:
def twice
yield
yield
end
twice { puts "Chunky Bacon!" }Step through the cell with ⏯: at every yield, Ruby jumps out of the method into the block and back again afterwards. The block isn't inside the parentheses, it hangs on behind the call – that's why def twice needs no parameter for it.
It gets interesting with values. yield(dish, price) hands the block values, which it receives between the |…|. And whatever the block works out as its last value comes back into the method as the result of yield. The same method, two blocks, two results:
def price_tag(dish, price)
text = yield(dish, price)
"[ #{text} ]"
end
puts price_tag("bacon", 4.5) { |what, price| "#{what} for #{price} francs" }
puts price_tag("egg", 1.2) { |what, price| "#{what.upcase}!!! #{price}" }The method decides when something happens and with which values – the block decides what. That's exactly how map works: it knows the list, you supply the transformation.
And if no block comes along at all? Then yield has nothing to call:
twiceLocalJumpError: no block given (yield) – no block was handed over. With block_given? a method asks first whether there is one. That makes the block optional: whoever passes one decides for themselves, whoever doesn't gets the usual answer:
def welcome(name)
if block_given?
yield(name)
else
"Hello, #{name}!"
end
end
p welcome("Kaz")
p welcome("Kaz") { |n| "Howdy, #{n}! Bacon?" }A popular pattern is the sandwich: the method does something before and something after, and the block is the filling in the middle. What goes in, every call decides for itself:
def sandwich
puts "🍞 bread"
yield
puts "🍞 bread"
end
sandwich { puts "🥓 bacon" }
sandwich do
puts "🥚 egg"
puts "🧀 cheese"
endRuby itself is full of sandwiches: File.open("notes.txt") { |file| … } opens a file, hands it to your block and closes it again afterwards, whatever the block does – lesson 49 shows it. And now the best part: each is no magic either. With while, a counter and yield you can write it yourself – ⏯ shows you how the method jumps into the block once for every element:
def each_of(list)
i = 0
while i < list.length
yield(list[i])
i += 1
end
list
end
foxes = ["Chunky", "Kaz", "Isi"]
each_of(foxes) { |name| puts "Enjoy your meal, #{name}!" }Like the real each, each_of returns the list itself at the end. And map? That's an each that collects the block's results. So map_of builds on each_of: for every element it calls its own block with yield(x) and puts the result into the new array. A yield always belongs to the method it's written in – even when it sits inside a little block for each_of:
def map_of(list)
result = []
each_of(list) { |x| result << yield(x) }
result
end
p map_of([1, 2, 3]) { |n| n * 10 }
map_of(foxes) { |name| name.length }Sometimes a method doesn't want to call the block itself at all, only pass it on to another one. Then it gives the block a name: &block as the last parameter catches the block in a variable, and &block in a call hands it on, just as if it had been written there:
def for_all_foxes(&block)
["Chunky", "Kaz", "Isi"].map(&block)
end
for_all_foxes { |fox| "#{fox} 🥓🥓🥓" }The variable block holds a Proc object – a block you can carry around. What else you can do with it (procs and lambdas) is shown in lesson 114. For a start, this rule of thumb is enough: write yield when your method calls the block itself, and &block when it only passes it on. yield(x) gives the block values and brings its result back, and block_given? makes it optional.
repeat(n): the method calls its block n times, with the numbers 1, 2, … up to n, and returns the block's results as an array. repeat(4) { |i| i * i } gives [1, 4, 9, 16], repeat(3) { |i| "🥓" * i } gives ["🥓", "🥓🥓", "🥓🥓🥓"].# def repeat(n)
# ... # call the block with 1, 2, ... n
# ... # and return its results as an array
# end
# repeat(4) { |i| i * i }select – without using select, filter or reject: sift(list) returns a new array with the elements for which the block gives something true. sift([3, 8, 12, 5]) { |n| n.even? } gives [8, 12]. And without a block, sift sifts nothing out: sift([3, 8]) returns the whole list.# def sift(list)
# ... # without a block: the whole list
# ... # otherwise: only the elements the block says true to
# end
# sift([3, 8, 12, 5]) { |n| n.even? }