A block is simply a chunk of code, and yield allows you to "inject" that code at some place into a function. So if you want your function to work in a slightly different way where you don't have to write a whole new function,you can instead reuse a method you already have, but give it a different block.
Consider a function that will print the members of an Array, but number them, like this: if you give it ["apple","banana"], it should print
1. apple
2. banana
Easy enough, right? There are several ways to do this, but I'll just use each and a counter.
def print_list(array)
counter = "a"
array.each do |item|
puts "#{counter}. #{item}"
counter = counter.next
end
end
Because I chose .next
over += 1 to increment the counter, and because Ruby is really awesome, we can use strings instead of numbers to label the list items: "a".next is "b", and so forth.
Great, right? But what if we wanted a different format for the item labels? Say, (1), (2), (3) instead of 1., 2., 3.? Our function does the formatting in this line:
puts "#{counter}. #{item}"
So instead of having two (almost identical) functions – one for 1. 2. and one for (1) (2) (and so on, one for every possible idea), we're going to export that formatting thing into a block, and have just a yield inside the function.
Create the following list formatting using yield
.
(a) Ruby
(b) Python
(c) Java
<10> Ruby
<11> Python
<12> Java
Create the following list formatting using yield
.
(i) Ruby
(ii) Python
(iii) Java
[500]: alpha
[600]: beta
[700]: gamma
[800]: delta
def print_list(array, counter = 1)
array.each do |item|
puts "#{yield counter} #{item}"
counter = counter.next
end
end
print_list(["the", "word"]) do |n|
"(#{'i' * n})"
end
the key takeaway from this challenge is that you can yield anywhere, even inside an interpolated string
you then let the block do the work for you
try to use yield in some basic ruby challenges, just try stuff out