Skip to content

Instantly share code, notes, and snippets.

@harrisonmalone
Last active October 7, 2018 22:11
Show Gist options
  • Save harrisonmalone/c5e9fae117939e7439fb0932d5e94d3e to your computer and use it in GitHub Desktop.
Save harrisonmalone/c5e9fae117939e7439fb0932d5e94d3e to your computer and use it in GitHub Desktop.

Yield challenge

What is a block?

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.

Use cases for yield

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.

Challenge

Create the following list formatting using yield.

(a) Ruby
(b) Python
(c) Java
<10> Ruby
<11> Python
<12> Java

Beast mode

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment